如何计算排队多少个字?更智能的方式

How to count how many words are in line?Smarter way?

本文关键字:智能 方式 多少 何计算 计算 排队      更新时间:2023-10-16

如何找出有多少个单词?我现在的方法,你数一下有多少空间。但是,如果有人击中 2 个空格或用空格开始线怎么办。

有没有其他或更聪明的方法可以解决这个问题?

我解决它的方式或我的代码有什么评论吗?

我是这样解决的:

#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
int main( )
{
    char str[80];
    cout << "Enter a string: ";
    cin.getline(str,80);
    int len;
    len=strlen(str);
    int words = 0;
    for(int i = 0; str[i] != ''; i++) //is space after character
    {
        if (isalpha(str[i])) 
        {
            if(isspace(str[i+1]))
            words++;
        }       
    }
    if(isalpha(str[len]))
    {
        words++;
    }
    cout << "The number of words = " << words+1 << endl;
    return 0;
}

标准单行代码是:

words= distance(istream_iterator<string>(istringstream(str)), istream_iterator<string>());
默认情况下会

跳过空格(多个(。

因此,如果您执行以下操作:

string word;
int numWords = 0;
while (cin >> word) ++numWords;

这应该计算简单情况下的单词数(不考虑单词的格式,跳过空格(。

如果你想要每行,你可以先读取该行,从字符串创建一个流,然后做类似的事情,如下所示:

string line, word;
int wordCount = 0;
getline(cin, line);
stringstream lineStream(line);
while (lineStream >> word) ++wordCount;

您不应该使用cin.getline,而应该更喜欢 free 函数 std::getline ,它接受一个可以增长的字符串并防止堆栈溢出 (lol(。坚持使用免费功能以提高安全性。

首先,你需要一个非常具体的"单词"定义。 大多数答案给出的计数与您的尝试略有不同,因为您对构成单词的定义不同。 您的示例特别要求在某些位置使用字母字符。 基于流的答案将允许任何非空格字符成为单词的一部分。

一般的解决方案是提出一个单词的精确定义,将其转换为正则表达式或有限状态机,然后计算匹配的每个实例。

下面是一个示例状态机解决方案:

std::size_t CountWords(const std::string &line) {
    std::size_t count = 0;
    enum { between_words, in_word } state = between_words;
    for (const auto c : line) {
        switch (state) {
            case between_words:
                if (std::isalpha(c)) {
                    state = in_word;
                    ++count;
                }
                break;
            case in_word:
                if (std::isspace(c)) state = between_words;
                break;
        }
    }
    return count;
}

需要考虑的一些测试用例(并突出了单词定义之间的差异(:

  • ""空字符串
  • " "只是空间
  • "a"
  • " one "
  • "count two"
  • "hyphenated-word"
  • ""That's Crazy!" she said."字母字符和相邻空格之间的标点符号
  • "the answer is 42"数字应该算作一个词?