繁体   English   中英

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

[英]Searching for a specific char in a array of strings in c++

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

例子:

用户输入字符串: 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!";

与其手动编写 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';
}

程序输出为

count = 3

如果您的编译器支持 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';
}

程序输出再次是

count = 3

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

for (int i = 0; i < 3; i++)
{
    if (userString[i] == userChar)
    {
        counter++;
    }
}

是不正确的。 您需要一个内部 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM