Golang-Based Program for counting the number of words within a string, all based on user input.
This program has been created for testing a different approach towards learning Golang: following the 'Question Driven Development' that aims towards learning thigs by doing.
Create an infinite shell until user has written "exit" on console:
1. Let user enter a string or paragraph
2. Let user search for a particular word that they want to find word count of
3. Print the number of times a word was mentioned in the entered string
Creating Shell - Can be done with a for loop Scanning for input - Can be done with fmt.Scanln Scanning for word-to-search - Can be done with fmt.Scanln Finding word-count - For-Loop to range over the user input
- Let User Enter & Search String Faced problem with scanner:
fmt.Println("\nPlease enter the string!")
fmt.Scanln("%s", &input)
- Program would end without taking user-input
- Input not taken by fmt.Scanf or fmt.Scanln
- Solved: fmt Scan family scan space-separated tokens. Instead of %s (string), use %q (quoted string) )and enter string within "quotes"
Instead we could have used bufio to provide a temporary storage:
scanner := bufio.NewScanner(os.Stdin)
input = scanner.Text()
scanner.Scan()
input = scanner.Text()
fmt.Printf("The enter input is: %s\n", input)
- Buffered vs unbuffered IO
- Table Difference
- Stop being distracted by theory all the time - Try to finish using whatever method you already know
- Range over input and scan how many times specific word mentioned
- Referred to this guide
- Basic blueprint:
wordCount := 0
for _, singleInput := range splitInput {
if word == singleInput {
wordCount++
}
}
fmt.Printf("The KeyWord %s is found %d times\n", word, wordCount)