21xrx.com
2025-03-26 14:44:27 Wednesday
文章检索 我的文章 写文章
如何用C++计算字符串中单词的数量?
2023-06-28 08:21:46 深夜i     29     0
C++ 字符串 单词数量 计算

在C++中,可以通过遍历字符串来计算其中单词的数量。在遍历字符串时,可以判断当前字符是否为单词的开始或结束,以此来确定单词的数量。

以下是一个实现代码的示例:

#include <iostream>
#include <string>
using namespace std;
int countWords(string str) {
  int count = 0;
  // 标记当前是否处于单词中
  bool inWord = false;
  for (int i = 0; i < str.size(); i++) {
    char c = str[i];
    // 判断当前字符是否为单词的开始或结束
    if (c == ' ' || c == '\n' || c == '\t')
      inWord = false;
     else if (!inWord) {
      inWord = true;
      count++;
    }
  }
  return count;
}
int main() {
  string str = "Hello world, this is a test string.";
  int count = countWords(str);
  cout << "The number of words in the string is: " << count << endl;
  return 0;
}

通过运行上述代码,可以得到输出结果为:

The number of words in the string is: 8

可以看出,上述代码成功地计算出了字符串中的单词数量。在实际应用中,同样可以通过类似的方式,将字符串中的单词数量计算出来,以进行更为复杂的字符串处理等操作。

  
  

评论区

请求出错了