如何计算字符串中的单词数?

时间:2016-03-31 03:50:37

标签: c++ string

我已提示用户在我的程序的main函数中输入一个字符串并将其存储为userString,并希望显示有多少单词。

这是我打算从main调用的函数:

int countWords(string d) {
    string words = " ";
    for (int e = 0; e < d.length(); e++) {
        if (isspace(d[e])) {
            cout << "The string " << words << "word(s). ";
        }
    }
    return words;
}

我在某处读到函数应该实际计算空格的数量(这就是我使用isspace()的原因),而不是单词本身。

如何计算字符串中的单词数并将其显示在同一个函数中?我无法弄清楚它并且我得到了错误。

我也不能使用库函数。

预期产出:

  • 字符串&#34; 2020&#34;有一个字。
  • 字符串&#34; Hello guys&#34;有两个字。

3 个答案:

答案 0 :(得分:1)

如果您不想使用boost,可以使用简单的for循环。

#include <cctype>

...

for(int i = 0; i < toParse.length(); i++){
    if (isblank(toParse[i])){
        //start new word
    }
    else if (toParse[i] == '.'){
        //start new sentence
    }
    else if (isalphanum(toParse[i])){
        //add to your current word
    }
}

编辑:您只需增加一个整数,就可以看到//start new word.

答案 1 :(得分:0)

尝试boost::split(),将单词放入向量

答案 2 :(得分:0)

另外,如果你想计算满足某种条件的范围内的某些东西,你可以在std::count_if中思考

示例:

int countWords(std::string d) 
{
    int w = std::count_if(d.begin(), d.end(), [](char ch) { return isspace(ch); });
    std::cout << "The string \"" << d << "\" has " << w + 1 << " words." << '\n';
    return w;
}