统计字符串中某种字符的出现次数,可以用 STL 的 count 函数。
#include <bits/stdc++.h>
using namespace std;
signed main() {
string s;
cin >> s;
cout << count(s.begin(), s.end(), '1');
return 0;
}或者使用 count_if 函数。
#include <bits/stdc++.h>
using namespace std;
signed main() {
string s;
cin >> s;
cout << count_if(s.begin(), s.end(),
[&](char c) {
return c == '1';
});
return 0;
}