gpt4 book ai didi

c++ - 试图在不计算空格的情况下找到单词的数量

转载 作者:行者123 更新时间:2023-11-30 01:34:30 25 4
gpt4 key购买 nike

我试图从用户输入中找到单词的数量,但我被要求不要通过计算空格来找到它,因为用户可以输入一个字母和一堆空格,它会将其计为数字单词

我试过计算空格数,但我想不出另一种方法来计算单词数

char Array[100];
{
//variable declaration
int words = 0;
// input
cout << "Enter string: ";
cin.getline(Array, 100);
// Number of words
for (int i = 0; i < strlen(Array); i++)
{
if (Array[i] == ' ')
words++;
}
cout << "Number of words in the string are: " << words + 1;
cout << endl;
}

我想用另一种方法找到单词的数量,而不是通过空格的数量来计算它。感谢任何帮助。我是初学者,所以你能不能使用像 getloc 这样复杂的东西来解决问题。

最佳答案

您只需计算空格字符后紧跟非空格字符的次数。

int firstNonSpace = 0;

while (Array[firstNonSpace] == ' ') //to skip spaces at the beginning of input
{
firstNonSpace++;
}
for (int i = firstNonSpace; i < strlen(Array) - 1; i++)
{
if (Array[i] == ' ' && Array[i+1] != ' ')
words++;
}

if(words || firstNonSpace == 0)
words++; //do not increment if the input is empty or only spaces.
cout << "Number of words in the string are: " << words;

参见 Live Demo

请注意,您必须处理输入超出数组边界的情况,以免遇到未定义的行为。

关于c++ - 试图在不计算空格的情况下找到单词的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56181251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com