计算一个字符串在另一个字符串中每个字符的出现次数

时间:2019-04-02 03:53:21

标签: c++

我正在尝试编写一个函数,该函数将两个字符串作为参数,并返回第二个字符串的每个字符在第一个字符串中出现多少次的总计数。

例如,i = count("abracadabra", "bax");将返回7

我希望利用STL。我编写了以下函数来计算一个字符串中出现一个char的次数,但是在循环中调用此函数来解决上述问题似乎效率很低。

int count(const std::string& str, char c)
{
    int count = 0;
    size_t pos = str.find_first_of(c);
    while (pos != std::string::npos)
    {
        count++;
        pos = str.find_first_of(c, pos + 1);
    }
    return count;
}

1 个答案:

答案 0 :(得分:1)

您可以修改count函数以接受std::string作为第二个参数,然后一次循环一个字符,并使用std::count计算每个字符的出现次数并递增总数

#include <iostream>       // std::cout
#include <string>         // std::string
#include <algorithm>     // std::count

int count(const std::string& search, const std::string& pattern)
{
    int total = 0;
    for(auto &ch : pattern) {
        total += std::count(search.begin(), search.end(), ch);
    }

    return total ;
}

int main ()
{
    std::string hay("abracadabra");
    std::string needle("bax");

    std::cout << count(hay, needle) << std::endl;
    return 0;
}
相关问题