5

Trying to find the longest word using Go from a sentence.

At the moment I am using this method:

func longestWord(s string) string {

    newArr := strings.Split(s, " ")

    l := len(newArr[0])
    long := newArr[0]
    var result string
    // fmt.Println(long)
    for _, lenString := range newArr {

        if len(lenString) > l {
            // ll := len(lenString)
            // l := len(lenString)
            d := &l
            p := &long
            c := &result
            *d = len(lenString)
            *p = lenString
            *c = lenString
            // fmt.Println(lenString)
        } else {
            c := &result
            *c = newArr[0]
        }

    }
    return result
}

func main() {
    args := "Monday Tuesday Friday Sunday Wednesday"
    fmt.Println(longestWord(args))
}

But I'm not sure that this is the best method to achieve that. Is there any other elegant way to do that? I know that there is one more method by using sort, but I would prefer more using the way with iteration between words.

1
  • 1
    Beware: ranging over a string will range over the number of bytes, which isn't always the same as the number of characters (Hi is 2 bytes long while 世界 is 6 bytes long). To range over the number of characters, use i, c := range []rune(str). And, if you're targeting a terminal as the final output, consider go-runewidth when measuring the width of monospaced characters.
    – Roshambo
    Nov 30, 2020 at 21:08

3 Answers 3

7

"Best" solution

We can even write it more compact than the other answers by taking advantage of the following:

  • using tuple assignments
  • initializing the best and its length with the zero values ("" and 0) and omitting the check for 0 words as the for range handles that properly
  • no need to store words as a local variable as it is only used in the loop

We lose nothing from readability:

func longestWord(s string) string {
    best, length := "", 0
    for _, word := range strings.Split(s, " ") {
        if len(word) > length {
            best, length = word, len(word)
        }
    }
    return best
}

Testing it:

fmt.Printf("%q\n", longestWord(""))
args := "Monday Tuesday Friday Sunday Wednesday"
fmt.Printf("%q\n", longestWord(args))

Output (try it on the Go Playground):

""
"Wednesday"

Most compact solution

Note that storing the length of the best is optional and is purely for optimization purposes, since if we have best, its length is always len(best).

Taking advantage of this, and that we can use named result parameters (and that all variables are initialized to the zero value of their types unless an initial value is provided–which for string is ""), we can even write it more compact, again losing nothing from readability:

func longestWord(s string) (best string) {
    for _, word := range strings.Split(s, " ") {
        if len(word) > len(best) {
            best = word
        }
    }
    return
}

Testing and output is the same, try it on the Go Playground. Again, in most cases this is probably slightly slower compared to when we stored the length too.

4

That totally works! You could make it a bit shorter, while also using longer variable names that explain a bit more about your intention.

func longestWord(s string) string {
    words := strings.Split(s, " ")
    if len(words) == 0 {
        return ""
    }
    best := words[0]
    best_length := 0
    for _, word := range words {
        if len(word) > best_length {
            best = word
            best_length = len(word)
        }
    }
    return best
}

You could change this to track a pointer instead of the word itself if you like.

1

I would do it like this:

func longestWord(s string) string {

newArr := strings.Split(s, " ")

longestWord := ""
longestLength := 0

    // loop through the array
    for _, word := range newArr {
        // save length of word in the actual iteration
        length := len(word)

        // if length is larger, than longest
        if length > longestLength {
            // save the new longest word
            longestWord = word
            longestLength = length
        }
    }


// return the longest word
return longestWord
}

Implementation can be found on the go playground

1
  • 1
    No need to check if array is not empty (if len(newArr) > 0) as in that case the range loop is just not entered. IOW it is safe to have range loop over empty array.
    – ain
    Aug 26, 2018 at 20:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.