C++中统计大写字母、小写字母、特殊字符和数字
给定一个包含大写字母、小写字母、特殊字符和数字值的字符串。任务是计算字符串中所有类型字符、特殊字符和数字值的频率。
大写字母 − A - Z,ASCII 值范围为 65 - 90(包含 65 和 90)。
小写字母 − a - z,ASCII 值范围为 97 - 122(包含 97 和 122)。
数字值 − 0 - 9,ASCII 值范围为 48 - 57(包含 48 和 57)。
特殊字符 − !, @, #, $, %, ^, &, *
输入 − str = Tutori@lPo!n&90
输出 − 字符串中大写字母的总数为 − 2
字符串中小写字母的总数为 − 8
字符串中数字的总数为 − 2
字符串中特殊字符的总数为 − 3
输入 − str = WELc0m$
输出 − 字符串中大写字母的总数为 − 3
字符串中小写字母的总数为 − 2
字符串中数字的总数为 − 1
字符串中特殊字符的总数为 − 1
下面程序中使用的方案如下
输入包含大写字母、小写字母、特殊字符和数字值的字符串。
计算字符串的长度。
使用变量存储大写字母、小写字母、特殊字符和数字值的计数,并将其初始化为 0。
从 0 到字符串大小开始 FOR 循环。
在循环内,检查 IF str[i] >= A 且 str[i] <= Z,则递增大写字母的计数。
在循环内,检查 IF str[i] >= a 且 str[i] <= z,则递增小写字母的计数。
在循环内,检查 IF str[i] >= 0 且 str[i] <= 9,则递增数字值的计数。
否则,递增特殊字符的计数。
打印结果。
示例
#include<iostream>
using namespace std;
//Count Uppercase, Lowercase, special character and numeric values
void count(string str){
int Uppercase = 0;
int Lowercase = 0;
int digit = 0;
int special_character = 0;
for (int i = 0; i < str.length(); i++){
if (str[i] >= 'A' && str[i] <= 'Z'){
Uppercase++;
}
else if(str[i] >= 'a' && str[i] <= 'z'){
Lowercase++;
}
else if(str[i]>= '0' && str[i]<= '9'){
digit++;
}
else{
special_character++;
}
}
cout<<"Total Upper case letters in a string are: "<<Uppercase<< endl;
cout<<"Total lower case letters in a string are: "<<Lowercase<< endl;
cout<<"Total number in a string are: "<<digit<< endl;
cout<<"total of special characters in a string are: "<<special_character<< endl;
}
int main(){
string str = "Tutori@lPo!n&90";
count(str);
return 0;
}输出
如果运行以上代码,它将生成以下输出:
Total Upper case letters in a string are: 2 Total lower case letters in a string are: 8 Total number in a string are: 2 total of special characters in a string are: 3
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP