计算一条英文句子中单词个数

2014-11-24 02:32:59 · 作者: · 浏览: 1

给定一句英文,除了字母之外,还包含空格回车和水平制表符号('\t', '\n'), 根据这三个符号来计算一句英文中所含有单词的个数。

下面给出的这个方法是我从一个国外网站上看到的,思路清晰而且很有逻辑性,于是决定记录下来:

设定两个标志: IN, OUT和一个变量state,当遇到字母的时候state值为IN, 当遇到上面说的那三个字符的时候state为OUT。你可以测试任何情况,包括两个单词中间有多个空格的情况,下面给出代码:


[cpp]
#include
#include
using namespace std;

unsigned int count_word(char *s) {
const int OUT = 0;
const int IN = 1;
int state = OUT;
unsigned int count = 0;
while (*s) {
if (*s == ' ' || *s == '\t' || *s == '\n')
state = OUT;
else if (OUT == state) {
state = IN;
++count;
}
s++;
}
return count;
}

int main(int argc, char *argv[]) {
char s[] = "this is a test\n this is a test";
cout << count_word(s) << endl;
cin.get();
return 0;
}

#include
#include
using namespace std;

unsigned int count_word(char *s) {
const int OUT = 0;
const int IN = 1;
int state = OUT;
unsigned int count = 0;
while (*s) {
if (*s == ' ' || *s == '\t' || *s == '\n')
state = OUT;
else if (OUT == state) {
state = IN;
++count;
}
s++;
}
return count;
}

int main(int argc, char *argv[]) {
char s[] = "this is a test\n this is a test";
cout << count_word(s) << endl;
cin.get();
return 0;
}