我正在尝试编写一个将两个字符串作为参数并返回第二个字符串的每个字符在第一个字符串中出现多少次的总计数的函数。
例如,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;
}
最佳答案
您可以修改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;
}
关于c++ - 计算一个字符串在另一个字符串中每个字符的出现次数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55466722/