Project 10: Longest word finder
Complete video course: Udemy
Introduction
Longest word finder is a program that determines the longest word in a string of text and displays it to the user.
The user is prompted for some text, the program determines the longest word and finally displays the result to the user.
Practical
Boilerplate code:
package main
import (
)
func main() {
}
As with the word counter project, we will prompt the user for a string of text which could be a single word, a sentence, a paragraph, or even longer. We will therefore use the bufio package just as before:
import (
"bufio"
"fmt"
"os"
)
var text string
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter a sentence or paragraph:")
text, _ = reader.ReadString('\n')
Next, we will create a new function called findLongestWord in which we shall implement the logic for finding and returning the longest word in a string of text passed to it. We will use the Fields function of the strings package to break down the user-provided text into a collection of individual words. So, let us update the imports section:
import (
"bufio"
"fmt"
"os"
"strings" // add this
)
We then define the function:
func findLongestWord(text string) string {
longestWord := ""
maxLength := 0
words := strings.Fields(text)
for _, word := range words {
if len(word) > maxLength {
longestWord = word
maxLength = len(word)
}
}
return longestWord
}
In the above snippet, we first declare 2 variables: longestWord and maxLength . These will hold the longest word and keep track of the maximum word length respectively. We then split the user-provided string into a collection of words which we store in the words variable.
Next, we use a for loop (in this case to loop through a collection), in each case comparing the length of the word to the last maxLength value. Using the range keyword returns 2 values in each iteration: current index, and current value. Of interest to us is the value, hence the blank identifier in place of the index value.
If the word’s length is greater, we update the longestWord and maxLength values to contain this word and its length respectively. Finally, we return the longest word found.
Back in the main function, we can now call the above function and store the result in a variable before displaying it to the user:
longestWord := findLongestWord(text)
fmt.Printf("The longest word is: %s\n", longestWord)
Complete code:
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func findLongestWord(text string) string {
longestWord := ""
maxLength := 0
words := strings.Fields(text)
for _, word := range words {
if len(word) > maxLength {
longestWord = word
maxLength = len(word)
}
}
return longestWord
}
func main() {
var text string
reader := bufio.NewReader(os.Stdin)
fmt.Println("Enter a sentence or paragraph:")
text, _ = reader.ReadString('\n')
longestWord := findLongestWord(text)
fmt.Printf("The longest word is: %s\n", longestWord)
}