c++ - 计算一个字符串的每个字符在另一个字符串中的出现次数
问题描述
我正在尝试编写一个函数,该函数将两个字符串作为参数并返回第二个字符串的每个字符出现在第一个字符串中的次数的总数。
例如,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;
}
解决方案
您可以修改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;
}
推荐阅读
- java - Spring boot:如何使 ContentType 标头完全可选?如果未通过,它会抛出 HttpMediaTypeNotSupportedException
- python - 将“requests_html”与“FastAPI”一起使用
- selenium-chromedriver - selenium -> chromedriver.exe -> 消息:未知错误:找不到 Chrome 二进制文件
- python - 从 Python 中的多人属性列表中为 n 人创建一些列表
- ssh - 通过 SSH 连接到 Raspberry PI 时出现问题
- python - 如何强制 Pygame 2.0.0 使用最新版本的 SDL?
- javascript - JS中的Bigint破坏了数组排序?
- android - 在视图变得不可见后执行任务
- exchange-server - Exchange 2013 与会者响应始终为空
- python - 卡夫卡消费者无法阅读新的味精?