c++ - 无法在我的字符串中找到准确数量的以标点符号(如引号)开头的单词

标签 c++ string count words punctuation

我正在编写一个代码,我应该在其中查找字符串中的单词数,因为我知道每个单词都可以由 A-Z(或 a-z)以外的任何字符分隔。我写的代码只有在句子开头没有标点符号的情况下才能正常工作。但是,当句子以引号等标点符号开头时,问题就来了(即“仅连接。”结果将显示 3 个单词,而不是 2 个)。我正在使用 Dev-C++ 在 C++ 中编程。您的帮助将不胜感激。我的代码如下:

#include <cstring>
#include <iostream>
#include <conio.h>
#include <ctype.h>

using namespace std;

int getline();   //scope
int all_words(char prose[]);  //scope

int main()
{
   getline();
   system ("Pause");
   return 0;
}


int getline()
{
    char prose[600];
    cout << "Enter a sentence: ";

    cin.getline (prose, 600); 
    all_words(prose);
    return 0;
}


int all_words(char prose[])
{ int y, i=0, k=0; int count_words=0; char array_words[600], c;

    do
     {

        y=prose[i++];
        if (ispunct(y))  //skeep the punctuation
         i++;

         if ((y<65 && isspace(y)) || (y<65 && ispunct(y)))     //Case where we meet spacial character or punctuation follwed by space

          count_words++;   //count words

         if (ispunct(y))  //skeep the punctuation
           i++;

    }while (y); //till we have a character

    cout <<endl<<" here is the number of words  "<< count_words <<endl;

   return 0; 

 }



 ***********************************Output******************************
  Enter a sentence: "Only connect!"

  here is the number of words  3

  Press any key to continue . . .

最佳答案

我认为您需要重新考虑您的算法。在我的脑海中,我可能会这样做:

  • 在字符串未结束时循环
    • 跳过所有非字母字符(while (!std::isalpha))
    • 跳过所有字母字符 (while (std::isalpha))
    • 增加字数统计

请记住还要检查那些内部循环中的字符串结尾。

关于c++ - 无法在我的字符串中找到准确数量的以标点符号(如引号)开头的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12366422/

相关文章:

c++ - 从随机起始位置开始的螺旋阵列

c++ - 两个主要功能

python - 计算连续字符

c++ - 如何忽略空格和标点符号?

c 替代字符串枚举

mysql - SQL更新每行计数

JavaScript:数组中给定字符串的数量

c++ - OpenGL屏幕坐标到世界坐标

c++ - 数组长度,为什么从命令行中获取时不能使用它?

c# - 验证另一个字符串之间的字符串?