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
+9.6k Swift : Convert (cast) String to Integer
+13.3k Golang : ROT47 (Caesar cipher by 47 characters) example
+5.7k Golang : Humanize and Titleize functions
+7.9k Golang : GMail API create and send draft with simple upload attachment example
+6.4k Golang : Getting Echo framework StartAutoTLS to work
+15.2k Golang : Check if a string contains multiple sub-strings in []string?
+38.3k Golang : UDP client server read write example
+46.3k Golang : How to convert JSON string to map and slice
+11.1k Golang : Encrypt and decrypt data with x509 crypto
+4k MariaDB/MySQL : Form select statement or search query with Chinese characters
+19.2k Golang : Pipe output from one os.Exec(shell command) to another command
+15.1k Golang : Execute terminal command to remote machine example