C++使⽤字符函数统计字符串中各类型字符的个数
本题不是⽤字符数组读⼊的字符串,⽽是直接⽤了string类。我们可以⽤length函数直接判断字符串的长度,然后遍历字符串,对于遍历到的字符依次⽤函数检查每个字符属于哪⼀类,相应类的变量加1.
使⽤前三个函数检查字符即可,最后剩下的就是其他字符。
#include<iostream>
#include<string>
#include<bits/stdc++.h>
using namespace std;
int main(){
string str;
getline(cin, str);
int whitespace =0;
int digits =0;
int chars =0;
int others =0;
isalpha 函数
// write your
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;
return0;
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。