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
在上面的程序中,变量元音,辅音,数字和空格用于存储字符串中的元音,辅音,数字和空格的数量。for循环用于检查字符串的每个字符。如果该字符是元音,则元音变量将增加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