题解 | #使用字符函数统计字符串中各类型字符的个数#
使用字符函数统计字符串中各类型字符的个数
https://www.nowcoder.com/practice/31bdbc70188f48e995fa3cbef36613c8
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
getline(cin, str);
int whitespace = 0;
int digits = 0;
int chars = 0;
int others = 0;
// write your code here......
for (auto a: str)
{
if (a >= '0' && a <= '9')
++digits;
else if ((a >= 'a' && a <='z') || (a >= 'A' && a <= 'Z'))
++chars;
else if (a == ' ')
++whitespace;
else
++others;
}
cout << "chars : " << chars
<< " whitespace : " << whitespace
<< " digits : " << digits
<< " others : " << others << endl;
return 0;
}
使用范围for循环。范围for循环等价于:
char* str_point = &str[0];
while(*str_point != '\0')
{
if (*str_point >= '0' && *str_point <= '9')
++digits;
else if ((*str_point >= 'a' && *str_point <='z') || (*str_point >= 'A' && *str_point <= 'Z'))
++chars;
else if (*str_point == ' ')
++whitespace;
else
++others;
str_point++;
}
C++题解 文章被收录于专栏
记录在牛客网用C++刷题的题解思路
