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