单词的数目可以由空格出现次数决定(连续的若干个空格作为出现一次空格;一行开头的空格不统计在内)。若测出某一个字符为非空格,而它的前面的字符是空格,则表示“新的单词开始了”,此时是单词计数器加1,;若当前字符为为非空格,而其前面的也是非空格,则意味着仍是那个单词的继续,count值不应累加。前面的一个字符是否空格可以从word的值看出来,若word等于0,则表示前一个字符是空格,若word是1,意味着前面的字符是非空格。
1 package com.mianshi.easy;
2 public class Test1 {
3
4 public static int wordCount(String s){
5 int word = 0;
6 int count = 0;
7 for(int i=0; i<s.length(); i++){
8 if(s.charAt(i)==' '){
9 word = 0;
10 }else if(word == 0){
11 word = 1;
12 count++;
13 }
14 }
15 return count;
16 }
17
18 public static void main(String[] args) {
19
20 String s = "It is a good day!";
21 int i = Test1.wordCount(s);
22 System.out.println(s+"单词个数是: "+i);
23 }
24 }
结果:
It is a good day!单词个数是: 5
很可能写成:else if(s.charAt(i)!=' ' && word == 0),与程序中是一样的。
word在次数相当于一个标志位。