C++统计字符串中各类型字符的个数
·
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int letter = 0;
int digit = 0;
int space = 0;
int other = 0;
char buf[1024] = {0};
cin.getline(buf, sizeof(buf));
// write your code here......
for(int i = 0; buf[i] != '\0'; i++){ //遍历字符串到'\0'为止
char c = buf[i];
if(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') //大小写字母
letter++;
else if(c >= '0' && c <= '9') //数字
digit++;
else if(c == ' ') //空格
space++;
else //其他字符
other++;
}
cout << "letter:" << letter << " digit:" << digit << " space:" << space << " other:" << other << endl;
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int letter = 0;
int digit = 0;
int space = 0;
int other = 0;
char buf[1024] = {0};
cin.getline(buf, sizeof(buf));
// write your code here......
int len = strlen(buf);
for(int i = 0;i < len; i++){
if(isalpha(buf[i])){
letter++;
}else if(isdigit(buf[i])){
digit++;
}else if(isspace(buf[i])){
space++;
}else{
other++;
}
}
cout << "letter:" << letter << " digit:" << digit << " space:" << space << " other:" << other << endl;
return 0;
}
新一代开源开发者平台 GitCode,通过集成代码托管服务、代码仓库以及可信赖的开源组件库,让开发者可以在云端进行代码托管和开发。旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。
更多推荐


所有评论(0)