C++程式查詢字串中母音、子音、數字和空格的數量
字串是一維字元陣列,以空字元結尾。字串中可以包含許多母音、子音、數字和空格。
例如。
String: There are 7 colours in the rainbow Vowels: 12 Consonants: 15 Digits: 1 White spaces: 6
查詢字串中母音、子音、數字和空格數量的程式如下所示。
示例
#include <iostream>
using namespace std;
int main() {
char str[] = {"Abracadabra 123"};
int vowels, consonants, digits, spaces;
vowels = consonants = digits = spaces = 0;
for(int i = 0; str[i]!='\0'; ++i) {
if(str[i]=='a' || str[i]=='e' || str[i]=='i' ||
str[i]=='o' || str[i]=='u' || str[i]=='A' ||
str[i]=='E' || str[i]=='I' || str[i]=='O' ||
str[i]=='U') {
++vowels;
} else if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z')) {
++consonants;
} else if(str[i]>='0' && str[i]<='9') {
++digits;
} else if (str[i]==' ') {
++spaces;
}
}
cout << "The string is: " << str << endl;
cout << "Vowels: " << vowels << endl;
cout << "Consonants: " << consonants << endl;
cout << "Digits: " << digits << endl;
cout << "White spaces: " << spaces << endl;
return 0;
}輸出
The string is: Abracadabra 123 Vowels: 5 Consonants: 6 Digits: 3 White spaces: 1
在上面的程式中,變數 vowels、consonants、digits 和 spaces 用於儲存字串中母音、子音、數字和空格的數量。for 迴圈用於檢查字串的每個字元。如果該字元是母音,則 vowels 變數加 1。子音、數字和空格也是如此。演示此功能的程式碼片段如下所示。
for(int i = 0; str[i]!='\0'; ++i) {
if(str[i]=='a' || str[i]=='e' || str[i]=='i' ||
str[i]=='o' || str[i]=='u' || str[i]=='A' ||
str[i]=='E' || str[i]=='I' || str[i]=='O' ||
str[i]=='U') {
++vowels;
} else if((str[i]>='a'&& str[i]<='z') || (str[i]>='A'&& str[i]<='Z')) {
++consonants;
} else if(str[i]>='0' && str[i]<='9') {
++digits;
} else if (str[i]==' ') {
++spaces;
}
}計算出字串中母音、子音、數字和空格出現的次數後,就會顯示出來。這在以下程式碼片段中顯示。
The string is: Abracadabra 123 Vowels: 5 Consonants: 6 Digits: 3 White spaces: 1
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP