如何计算字符串中用户输入元素的出现次数?

How can I count the number of occurrences of a user inputed element in a string?

本文关键字:元素 输入 用户 何计算 计算 字符串      更新时间:2023-10-16

如何计算字符串中用户输入元素的出现次数? 例:

输入:ADEDDSDF输入:一个输出:1

你可以自己计算或使用stl

#include <algorithm>
#include <string>
int main()
{
constexpr char chFind = 'a';
std::string str = "abcabca";
// first solution
size_t num1 = 0;
for(size_t i = 0; i < str.size(); i++)
if (str[i] == chFind)
num1++;
// second solution
size_t num2 = std::count(str.begin(), str.end(), chFind);
return 0;
}