题目:
输入一个只包含'a','b','c'的字符串,问'a','b','c'分别出现了多少次。
具体做法:
题目代码中给了一个string字符串,并没有给出字符串的长度,我们可以使用C++中的迭代器来遍历循环,使用!=s.end(),可以使代码更加安全,他会自动识别是否到字符串的末尾,避免了越界访问的可能性。
具体代码写法如下
#include<iostream>
using namespace std;
int main() {
string s;
cin >> s;
// write your code here......
int a = 0, b = 0, c = 0;
for (auto it = s.begin(); it != s.end(); ++it) { //这里面的it是迭代器
if (*it == 'a') { //*it代表指向的字符,用it遍历字符串s
a ++; //如果*it指向的是字符啊,则a+1;
}
else if (*it == 'b')
{
b++;
}
else if (*it == 'c')
{
c++;
}
}
cout << a << ' ' << b << ' ' << c;
return 0;
}

京公网安备 11010502036488号