求给定字符串中的单词数

1. 题目:给定一个字符串,单词以' '或'\t'间隔,返回字符串中的单词个数。如输入:"\t  ab\tc  drf e ffrt\tert",输出为6。

2. 解答:

  (1)我的思路:遍历字符串,遇到非' '或'\t',则count++,然后while循环跳过之后的所有非' '或'\t';如果是' '或'\t',然后while循环跳过所有的' '或'\t'。这样每次遇到非' '或'\t',就说明新的单词出现了。

  (2)网站http://www.leetcode.com/2010/02/c-code-to-count-number-of-words-in.html#comment-23542给出的思路,设置一个inword flag。如果正在访问的字符在单词内部,则inword为true;如果正在访问的字符在单词外部,则inword为false。初始值为false。这种方法没有考虑'\t'的情况。

  (3)两种方法的比较:(1)比较直观,过滤掉' '或'\t',每次出现字母即出现新的单词;(2)思想是什么情况下代表新单词的出现,当inword为false,并且当前访问的是非空格时,即表示新的单词出现;当inword为true,并且当前访问的是字符是空格时,将inword置为false。

3. 代码:

View Code
 1 //思路1代码
 2 int wordCount(char* str)
 3 {
 4     assert(str);
 5     int count=0;
 6     char* p=str;
 7     while (*p!='\0')
 8     {
 9         //跳过所有空格
10         if ((*p==' ') || (*p=='\t'))
11         {
12             while ((*p!='\0') && ((*p==' ') || (*p=='\t')))
13             {
14                 p++;
15             }
16         }
17         else
18         {
19             count++;
20             //跳过所有非空格
21             while ((*p!='\0') && (*p!=' ') && (*p!='\t'))
22             {
23                 p++;
24             }
25         }
26     }
27     return count;
28 }
29 
30 //思路2代码
31 int countNumWords(const char *str) { 
32     assert(str);
33     bool inWord = false; 
34     int wordCount = 0; 
35     while (*str) { 
36         if (!inWord && isalpha(*str)) { 
37             inWord = true; 
38             wordCount++; 
39         } 
40         else if (inWord && *str == ' ') { 
41             inWord = false; 
42         } 
43         str++; 
44     } 
45     return wordCount; 
46 }
47 
48 int main()
49 {
50     char str[]="\t  ab\tc  drf e ffrt\tert";
51     cout<<wordCount(str)<<endl;
52     cout<<countNumWords(str)<<endl;
53     return 0;
54 }

 

posted @ 2012-08-09 16:55  kasuosuo  阅读(533)  评论(0编辑  收藏  举报