统计字符串中单词的个数

一,问题描述:

给定一个字符串,统计该字符串中有多少个单词。单词以空格、回车、TAB键 分隔。

比如: "    I come   from china"   有4个单词。

注意,字符串不一定以字母开头,也可以从空格开头。

二,实现思路:

使用一个 boolean isWhiteSpace用来标记当前字符所处的模式:比如,当前字符不是26个字母表中的字母时,说明 处在 ”空格模式“,即它是一个分隔符,而不是单词。

只有当从空格模式转化成 ”单词模式 “时,计数增1。

三,代码如下:

 1 public class WordCount {
 2     
 3     
 4     public static void main(String[] args) {
 5         String s = "  i    come from     china  ";
 6         int r = wordCount(s);
 7         System.out.println(r);
 8     }
 9     
10     //返回str中代表的单词个数
11     public static int wordCount(String str){
12         int count = 0;
13         boolean isWhiteSpace = true;//标记当前是否处在"空格"模式
14         for(int i = 0; i < str.length(); i++)
15         {
16             char c = str.charAt(i);
17             if(c == ' ' || c == '	' || c == '
')//如果碰到的是分隔符,else语句不会执行
18                 isWhiteSpace = true;
19             else if(isWhiteSpace)//当碰到非分隔符,刚好且 处在 "空格"模式时,单词计数加1
20             {
21                 count++;
22                 isWhiteSpace = false;
23             }
24         }
25         return count;
26     }
27 }
原文地址:https://www.cnblogs.com/hapjin/p/5379204.html