To find the longest word in a string, we can split the string by space characters and iterate over the resulting slice of words, keeping track of the longest word seen so far. Here's an example:
main.go353 chars21 lines
In this example, we start by declaring the input string and splitting it into a slice of words using the strings.Split()
function.
We then initialize a longestWord
variable to an empty string, which will hold the longest word found so far.
We then iterate over the slice of words using a for
loop, where for each word, we compare its length to the length of the current longest word. If the current word is longer, we update the longestWord
variable to that word.
Finally, we print out the resulting longestWord
variable.
gistlibby LogSnag