find the shortest word in a string in go

To find the shortest word in a string in Go, we can split the string into words using the strings.Split() function and then loop through the resulting words array, keeping track of the shortest word found so far. Here is an example code snippet:

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    s := "The quick brown fox jumps over the lazy dog"
    words := strings.Split(s, " ")
    shortestWord := words[0]

    for _, word := range words {
        if len(word) < len(shortestWord) {
            shortestWord = word
        }
    }

    fmt.Println("Shortest word:", shortestWord)
}
359 chars
21 lines

In this code, we first split the string s into words using strings.Split() and store the resulting array in words. We then set the shortestWord variable to the first word in the array.

We then loop through the words array using a for loop with range, comparing each word's length to that of the current shortest word stored in the shortestWord variable. If we find a word shorter than the current shortest, we update the shortestWord variable to that word.

Finally, we print out the shortestWord variable to the console using fmt.Println().

gistlibby LogSnag