/****************************************************************************** * 统计句子中的单词数。 * 算法:单词是用分隔符隔开的,因此,从开始遇到不为分割符的符号直到遇到分隔符,单词数加1. ********************************************************************************/ #include <iostream> #include <string> #include <utility> #include <vector> #include <map> #include <cctype> using namespace std; int main() { string str1 = "hello world,welcome\tchina.list:"; string str2 = "fys,zhang wang"; string str3 = "the end"; string str4 = str1 + str2 + str3; string seperators(" ,.\t:\n\r\f"); int wordCount = 0; string::size_type startPos = 0; string::size_type endPos = 0; while ((startPos = str4.find_first_not_of(seperators, endPos)) != string::npos) { //找不为分隔符的符号,记下位置; wordCount++; endPos = str4.find_first_of(seperators, startPos); //从上面的位置开始,一直到分隔符。 } cout << wordCount; return 0; }