天天看點

計算一條英文句子中單詞個數

給定一句英文,除了字母之外,還包含空格回車和水準制表符号('\t', '\n'), 根據這三個符号來計算一句英文中所含有單詞的個數。

下面給出的這個方法是我從一個國外網站上看到的,思路清晰而且很有邏輯性,于是決定記錄下來:

設定兩個标志: IN, OUT和一個變量state,當遇到字母的時候state值為IN, 當遇到上面說的那三個字元的時候state為OUT。你可以測試任何情況,包括兩個單詞中間有多個空格的情況,下面給出代碼:

#include<iostream>
#include<string>
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;
}