概述
给出一个句子,找出其中的单词数。句子中的每个词只有英文字母
例子
Input: "Hello World"
Output: 2
Input: "This is hat"
Output: 3
程序
以下是相同的程序。
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)
}
输出
2
3