How to find the longest word in a string with Go

1 Answer

0 votes
package main

import (
    "fmt"
    "strings"
)

func longestWord(s string) string {
    words := strings.Fields(s)
    longest := ""

    for _, w := range words {
        if len(w) > len(longest) {
            longest = w
        }
    }

    return longest
}

func main() {
    fmt.Println(longestWord("Could you recommend a good restaurant nearby?"))
}


/*
run:

restaurant

*/

 



answered Mar 3 by avibootz
...