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
+7.5k Golang : Mapping Iban to Dunging alphabets
+15.1k nginx: [emerg] unknown directive "ssl"
+5.4k PHP : Fix Call to undefined function curl_init() error
+5.6k Get website traffic ranking with Similar Web or Alexa
+16.3k Golang : Convert slice to array
+26.2k Golang : Get executable name behind process ID example
+11.8k Golang : Setup API server or gateway with Caddy and http.ListenAndServe() function example
+12.5k Golang : Remove or trim extra comma from CSV
+9.7k Golang : ffmpeg with os/exec.Command() returns non-zero status
+20.3k Golang : Pipe output from one os.Exec(shell command) to another command
+36.3k Golang : Validate IP address
+20.5k Golang : Read directory content with os.Open