统计一个句子中的单词个数

来源:互联网 发布:mac flash插件错误 编辑:程序博客网 时间:2024/04/30 23:15

要求:输入一个字符串,输出该字符串中的单词的个数,如" I am a college studnet. hei  hei",输出结果为7


思路:用一个while循环扫描整个字符串,先将单词个数初始化为0,当扫描到一个单词则sum++,关键是如何判断是否满足为一个单词,如果用字符指针pIndex指向当前处理字符,则满足*pIndex!=' '&&*(pIndex+1)==' '时即为一个单词,基于此思路代码如下:

#include<iostream>using namespace std;int countWord(char * pStr){int sum=0;while(* pStr)   {   if(* pStr==' ')   {    pStr++;   }   else   {   while(*pStr&&*pStr!=' ')   {    pStr++;   }   sum++;   }   }return sum;}void main(){char str[]={" I am a college studnet. hei  hei"};cout<<countWord(str)<<endl;}
程序运行结果如下:


1 0