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
+5.2k Golang : Intercept, inject and replay HTTP traffics from web server
+9.5k Golang : interface - when and where to use examples
+21.2k Golang : Encrypt and decrypt data with TripleDES
+11.8k Golang : Decompress zlib file example
+21.5k Golang : Setting up/configure AWS credentials with official aws-sdk-go
+16.2k Golang : Get IP addresses of a domain name
+8.1k Your page has meta tags in the body instead of the head
+3.4k Golang : Switch Redis database redis.NewClient
+19.9k Golang : How to get struct tag and use field name to retrieve data?
+6.6k Fix sudo yum hang problem with no output or error messages
+42.8k Golang : Get hardware information such as disk, memory and CPU usage
+6.2k Grep : How to grep for strings inside binary data