[英]Searching for a specific char in a array of strings in c++
The user has to enter 3 strings and we have to put them in an array.用户必须输入 3 个字符串,我们必须将它们放入一个数组中。 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.然后,如果找到 char,则更新计数器 char 出现的次数。
Example:例子:
User input string: Cat Car Watch
用户输入字符串: Cat Car Watch
User char input: a
用户字符输入: 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!";
Instead of writing for loops manually it is better to use standard algorithms as for example std::count
.与其手动编写 for 循环,不如使用标准算法,例如std::count
。
Here is a demonstration program这是一个演示程序
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
int main()
{
std::string words[] = { "Cat", "Car", "Watch" };
char c = 'a';
size_t count = 0;
for ( const auto &s : words )
{
count += std::count( std::begin( s ), std::end( s ), c );
}
std::cout << "count = " << count << '\n';
}
The program output is程序输出为
count = 3
If your compiler supports C++ 20 then you can write the program the following way如果您的编译器支持 C++ 20,那么您可以按以下方式编写程序
#include <iostream>
#include <string>
#include <iterator>
#include <ranges>
#include <algorithm>
int main()
{
std::string words[] = { "Cat", "Car", "Watch" };
char c = 'a';
size_t count = std::ranges::count( words | std::ranges::views::join, c );
std::cout << "count = " << count << '\n';
}
Again the program output is程序输出再次是
count = 3
As for your code then this code snippet至于你的代码,那么这个代码片段
for (int i = 0; i < 3; i++)
{
if (userString[i] == userChar)
{
counter++;
}
}
is incorrect.是不正确的。 You need one more inner for loop to traverse each string as for example您需要一个内部 for 循环来遍历每个字符串,例如
for (int i = 0; i < 3; i++)
{
for ( char c : userString[i] )
{
if ( c == userChar)
{
counter++;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.