Overview
Given a sentence find number of words in it. Each word in the sentence only has English letters
Example
Input: "Hello World"
Output: 2
Input: "This is hat"
Output: 3
Program
Here is the program for the same.
package main
import "fmt"
func countW(s string) int {
lenS := len(s)
numWords := 0
for i := 0; i < lenS; {
for i < lenS && string(s[i]) == " " {
i++
}
if i < lenS {
numWords++
}
for i < lenS && string(s[i]) != " " {
i++
}
}
return numWords
}
func main() {
output := countW("Hello World")
fmt.Println(output)
output = countW("This is hat")
fmt.Println(output)
}
Output
2
3