Golang : Find the shortest line of text example
Continue from previous tutorial on how to find the longest line in a given text. This example demonstrates how to find the shortest line in a given text file. Can be useful in a situation where you want to find shortest lines to discard from a raw data file.
Here you go!
package main
import (
"fmt"
"strings"
)
func shortestLine(input string) (shortest string) {
lines := strings.Split(input, "\n")
size := len(lines[0]) // init with first line length
for _, v := range lines {
//fmt.Println(k,v, "Size: ", len(v))
if len(v) <= size {
shortest = 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
shortest
no!`
//fmt.Println(text)
// find the shortest line in text and display it
fmt.Println("Shortest: ", shortestLine(text))
}
Shortest: no!
See also : Golang : Find the longest line of text example
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.7k Javascript : Put image into Chrome browser's console
+6.5k Golang : Check if password length meet the requirement
+6.1k Golang : Detect face in uploaded photo like GPlus
+19.9k Golang : How to get struct tag and use field name to retrieve data?
+9.5k Golang : ffmpeg with os/exec.Command() returns non-zero status
+10.6k Golang : Get UDP client IP address and differentiate clients by port number
+17.5k Golang : How to make a file read only and set it to writable again?
+14.3k Golang : Overwrite previous output with count down timer
+8k Prevent Write failed: Broken pipe problem during ssh session with screen command
+5.2k Golang : Reclaim memory occupied by make() example
+8.8k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+29.5k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?