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