【问题标题】:Counting the occurrences of every char of of one string in another string计算一个字符串的每个字符在另一个字符串中的出现次数
【发布时间】:2019-04-02 12:13:23
【问题描述】:

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

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

我希望使用 STL。我写了下面的函数来计算一个字符在一个字符串中出现了多少次,但是在循环中调用这个函数来解决上面的问题似乎效率很低。

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;
}

【问题讨论】:

  • std::find_first_of 可以用两个迭代器调用——一个用于要搜索的字符串,一个用于包含要搜索的字符的字符串。它在内部执行循环。

标签: c++


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-13
    • 2011-07-01
    • 2014-11-14
    • 1970-01-01
    • 2014-05-26
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多