Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding longest word in golang

Tags:

string

go

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.

like image 681
Ilie Soltanici Avatar asked Aug 26 '18 19:08

Ilie Soltanici


People also ask

How to find the longest word in string?

function findLongestWord(str) { var longestWord = str. split(' '). reduce(function(longest, currentWord) { return currentWord. length > longest.

How to find longest string in js?

function longest_str_in_array(arra) { let max_str = arra[0]. length; let ans = arra[0]; for (let i = 1; i < arra. length; i++) { const maxi = arra[i]. length; if (maxi > max_str) { ans = arra[i]; max_str = maxi; } } return ans; } console.


1 Answers

"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.

like image 94
icza Avatar answered Dec 06 '22 11:12

icza