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
+6.8k Web : How to see your website from different countries?
+5.3k PHP : Fix Call to undefined function curl_init() error
+40.7k Golang : How to count duplicate items in slice/array?
+27.1k Golang : dial tcp: too many colons in address
+5.2k Golang : Get S3 or CloudFront object or file information
+11.2k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+8.5k Golang : Find duplicate files with filepath.Walk
+22.5k Golang : simulate tail -f or read last line from log file example
+5.2k Golang : If else example and common mistake
+11k Use systeminfo to find out installed Windows Hotfix(s) or updates
+9k Golang : Temperatures conversion example
+11.9k Golang : Split strings into command line arguments