提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
键盘录入一句话,统计这句话中字母字符、数字字符、空白、标点符号和其它字符的个数。(使用字符函数实现)
输入描述:
键盘输入一个字符串
输出描述:
输出字符串中字母字符、数字字符、空白、标点符号和其它字符的个数。
示例1
输入:
hello123world,$ 123
输出:
chars : 10 whitespace : 1 digits : 6 others : 2
一、字符函数有哪些?
**
-这道题不是用字符数组读入的字符串,而是直接用了string类。我们可以用length函数直接判断字符串的长度,然后遍历字符串,对于遍历到的字符依次用函数检查每个字符属于哪一类,相应类的变量加1.
字符判断函数 作用
isalpha() 判断字符是否是字母(‘a’-‘z’ ‘A’-‘Z’)
isdigit() 判断字符是否是数字
isspace() 判断字符是否是空格、制表符、换行等标准空白
isalnum() 判断字符是否是字母或者数字
ispunct() 判断字符是标点符号
islower() 判断字符是否是小写字母(‘a’-‘z’)
isupper() 判断字符是否是大写字母(‘A’-‘Z’)
我们依次使用前三个函数检查字符即可,最后剩下的就是其他字符。
**
二、代码
#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(int i = 0; i < str.length(); i++){ //遍历字符串
if(isalpha(str[i])) //判断是否是字母
chars++;
else if(isdigit(str[i])) //判断是否是数字
digits++;
else if(isspace(str[i])) //判断是否是空格
whitespace++;
else
others++;
}
cout << "chars : " << chars
<< " whitespace : " << whitespace
<< " digits : " << digits
<< " others : " << others << endl;
return 0;
}
---
# 总结
本人在求解字符串长度是犯了一个错误,这个不是字符数组读入的字符串所以不能用strlen函数求长度,字符串类型直接用str.length()函数即可求解。