find the longest word in a string in go

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.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    str := "The quick brown fox jumps over the lazy dog."
    words := strings.Split(str, " ")

    longestWord := ""
    for _, word := range words {
        if len(word) > len(longestWord) {
            longestWord = word
        }
    }

    fmt.Println("Longest word:", longestWord)
}
353 chars
21 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