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;
}
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)