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.
function findLongestWord(str) { var longestWord = str. split(' '). reduce(function(longest, currentWord) { return currentWord. length > longest.
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.
We can even write it more compact than the other answers by taking advantage of the following:
best
and its length with the zero values (""
and 0
) and omitting the check for 0 words as the for range
handles that properlywords
as a local variable as it is only used in the loopWe 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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With