在 C++ 字符串数组中搜索特定字符

mat*_*atg 0 c++ string algorithm for-loop char

用户必须输入 3 个字符串,我们必须将它们放入一个数组中。然后用户输入他想要在输入字符串中查找的字符。然后,如果找到该字符,则更新该字符出现次数的计数器。

例子:

用户输入字符串:Cat Car Watch

用户字符输入:a

结果:

Letter a appears 3 times!

如何搜索这样的字符串数组以查找特定字符?

下面的代码,但我被卡住了:

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!";
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 6

与其手动编写 for 循环,不如使用标准算法,例如std::count

这是一个演示程序

#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';
}
Run Code Online (Sandbox Code Playgroud)

程序输出是

count = 3
Run Code Online (Sandbox Code Playgroud)

如果您的编译器支持 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';
}
Run Code Online (Sandbox Code Playgroud)

程序输出再次是

count = 3
Run Code Online (Sandbox Code Playgroud)

至于你的代码,那么这个代码片段

for (int i = 0; i < 3; i++)
{
    if (userString[i] == userChar)
    {
        counter++;
    }
}
Run Code Online (Sandbox Code Playgroud)

是不正确的。您还需要一个内部 for 循环来遍历每个字符串,例如

for (int i = 0; i < 3; i++)
{
    for ( char c : userString[i] )
    {
        if ( c == userChar)
        {
            counter++;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)