在C++中搜索一系列字符串中的特定字符
用户必须输入3个字符串,我们必须将它们放入数组中。 然后,用户输入了他想在输入字符串中找到的字符。 然后,如果找到炭,请更新计数器,以显示出现多少次char。
示例:
用户输入字符串:猫车观看
用户char输入:a
结果:
字母A出现3次!
如何通过字符串搜索这样的数组可以找到特定的炭?
下面的代码,但我卡住了:
string userString[3];
for (int i = 0; i < 3; i++)
{
cout << "Input string: ";
getline(cin, userString[i]);
}
char userChar;
cout << "Input char you want to find in strings: ";
cin >> userChar;
int counter = 0;
for (int i = 0; i < 3; i++)
{
if (userString[i] == userChar)
{
counter++;
}
}
cout << "The char you have entered has appeared " << counter << " times in string array!";
The user has to enter 3 strings and we have to put them in an array.
Then user enters a char that he wants to find in input strings.
Then if the char is found, update the counter for how many times char appeared.
Example:
User input string: Cat Car Watch
User char input: a
Result:
Letter a appears 3 times!
How can I search through a string array like this to find specific chars?
Code below but I'm stuck:
string userString[3];
for (int i = 0; i < 3; i++)
{
cout << "Input string: ";
getline(cin, userString[i]);
}
char userChar;
cout << "Input char you want to find in strings: ";
cin >> userChar;
int counter = 0;
for (int i = 0; i < 3; i++)
{
if (userString[i] == userChar)
{
counter++;
}
}
cout << "The char you have entered has appeared " << counter << " times in string array!";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
而不是手动编写循环,而是使用标准算法,例如
std :: count
。这是一个演示程序,
程序输出是
如果您的编译器支持C ++ 20,那么您可以再次以以下方式编写程序
输出
为您的代码,那么此代码段
是不正确的。您还需要一个内部循环才能穿越每个字符串,例如
Instead of writing for loops manually it is better to use standard algorithms as for example
std::count
.Here is a demonstration program
The program output is
If your compiler supports C++ 20 then you can write the program the following way
Again the program output is
As for your code then this code snippet
is incorrect. You need one more inner for loop to traverse each string as for example