题意:
输入一行字符,分别统计出包含英文字母、空格、数字和其它字符的个数。
方法一:
模拟
思路:直接遍历一遍字符串,统计出英文字母、空格、数字和其它字符的个数。最后输出。
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
while(getline(cin,s)){
int len=s.size();
int n1=0,n2=0,n3=0,n4=0;//统计英文字母、空格、数字和其它字符的个数
for(int i=0;i<len;i++){//遍历判断
if((s[i]>='a'&&s[i]<='z')||(s[i]>='A'&&s[i]<='Z')){//字母
n1++;
}else if(s[i]==' ')//空格
n2++;
else if(s[i]>='0'&&s[i]<='9')//数字
n3++;
else//其他字符
n4++;
}
printf("%d\n%d\n%d\n%d\n",n1,n2,n3,n4);//分别输出英文字母、空格、数字和其它字符的个数
}
return 0;
}
时间复杂度:
空间复杂度:![]()
方法一:
c++函数
思路:遍历字符串,根据c++自带函数来判断,isalpha()//字母isspace()//空格isdigit()//数字ispunct()//其他字符
统计出英文字母、空格、数字和其它字符的个数。最后输出。
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
while(getline(cin,s)){
int len=s.size();
int n1=0,n2=0,n3=0,n4=0;//统计英文字母、空格、数字和其它字符的个数
for(int i=0;i<len;i++){//遍历判断
if(isalpha(s[i])){//字母
n1++;
}else if(isspace(s[i]))//空格
n2++;
else if(isdigit(s[i]))//数字
n3++;
else if(ispunct(s[i]))//其他字符
n4++;
}
printf("%d\n%d\n%d\n%d\n",n1,n2,n3,n4);//分别输出英文字母、空格、数字和其它字符的个数
}
return 0;
}
时间复杂度:
空间复杂度:



京公网安备 11010502036488号