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
+71.9k Golang : How to convert character to ASCII and back
+10.5k Golang : convert(cast) string to integer value
+12.6k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+4.5k Golang : Map within a map example
+11.5k Golang : Gin framework accept query string by post request example
+28.5k Golang : How to check if a date is within certain range?
+5.8k Golang : Check to see if *File is a file or directory
+16.4k Golang : Count JSON objects and convert to slice/array
+7.6k Golang : List available AWS regions
+6.5k Android Studio : Import third-party library or package into Gradle Scripts
+23k Golang : Convert file content into array of bytes
+28.4k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions