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.go359 chars21 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