Golang : Find the longest line of text example
Ability to find the longest find in a given text file can be useful in a situation where you want to pre-process a raw data file. For example, you want to find the longest line and then word wrap or line break the longest line before actually processing the data.
Here you go!
package main
import (
"fmt"
"strings"
)
func longestLine(input string) (longest string) {
lines := strings.Split(input, "\n")
size := 0
for _, v := range lines {
//fmt.Println(k,v, "Size: ", len(v))
if len(v) >= size {
longest = v
size = len(v)
}
}
return
}
func main() {
text := `line 1
line 2 line 3 line 4
line 5 line 6 line 7 line 8 line 9 line 10
line 11 line 12
line 13 line 14 line 15`
//fmt.Println(text)
// find the longest line in text and display it
fmt.Println("Longest: ", longestLine(text))
}
Output:
Longest: line 5 line 6 line 7 line 8 line 9 line 10
Happy coding!
See also : Golang : Convert lines of string into list for delete and insert operation
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+13.1k Swift : Convert (cast) Int to String ?
+7.7k Golang : get the current working directory of a running program
+34k Golang : Call a function after some delay(time.Sleep and Tick)
+11.2k Golang : How to determine a prime number?
+12k Golang : Convert(cast) bigint to string
+6.4k Golang : How to get capacity of a slice or array?
+18.8k Unmarshal/Load CSV record into struct in Go
+8.3k Golang : Qt splash screen with delay example
+8.9k Golang : Sort lines of text example
+10.7k Golang : Flip coin example
+6.6k Golang : Spell checking with ispell example
+9.2k Golang : Serving HTTP and Websocket from different ports in a program example