原文: https://www.programiz.com/cpp-programming/examples/vowel-consonant-frequency-string

要理解此示例,您应该了解以下 C++ 编程主题:



示例 1:C 样式的字符串

该程序从用户那里获取 C 风格的字符串,并计算元音,辅音,数字和空格的数量。

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. char line[150];
  6. int vowels, consonants, digits, spaces;
  7. vowels = consonants = digits = spaces = 0;
  8. cout << "Enter a line of string: ";
  9. cin.getline(line, 150);
  10. for(int i = 0; line[i]!='\0'; ++i)
  11. {
  12. if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
  13. line[i]=='o' || line[i]=='u' || line[i]=='A' ||
  14. line[i]=='E' || line[i]=='I' || line[i]=='O' ||
  15. line[i]=='U')
  16. {
  17. ++vowels;
  18. }
  19. else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
  20. {
  21. ++consonants;
  22. }
  23. else if(line[i]>='0' && line[i]<='9')
  24. {
  25. ++digits;
  26. }
  27. else if (line[i]==' ')
  28. {
  29. ++spaces;
  30. }
  31. }
  32. cout << "Vowels: " << vowels << endl;
  33. cout << "Consonants: " << consonants << endl;
  34. cout << "Digits: " << digits << endl;
  35. cout << "White spaces: " << spaces << endl;
  36. return 0;
  37. }

输出

  1. Enter a line of string: This is 1 hell of a book.
  2. Vowels: 7
  3. Consonants: 10
  4. Digits: 1
  5. White spaces: 6

示例 2:字符串对象

该程序从用户那里获取一个字符串对象,并计算元音,辅音,数字和空格的数量。

  1. #include <iostream>
  2. using namespace std;
  3. int main()
  4. {
  5. string line;
  6. int vowels, consonants, digits, spaces;
  7. vowels = consonants = digits = spaces = 0;
  8. cout << "Enter a line of string: ";
  9. getline(cin, line);
  10. for(int i = 0; i < line.length(); ++i)
  11. {
  12. if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
  13. line[i]=='o' || line[i]=='u' || line[i]=='A' ||
  14. line[i]=='E' || line[i]=='I' || line[i]=='O' ||
  15. line[i]=='U')
  16. {
  17. ++vowels;
  18. }
  19. else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
  20. {
  21. ++consonants;
  22. }
  23. else if(line[i]>='0' && line[i]<='9')
  24. {
  25. ++digits;
  26. }
  27. else if (line[i]==' ')
  28. {
  29. ++spaces;
  30. }
  31. }
  32. cout << "Vowels: " << vowels << endl;
  33. cout << "Consonants: " << consonants << endl;
  34. cout << "Digits: " << digits << endl;
  35. cout << "White spaces: " << spaces << endl;
  36. return 0;
  37. }

输出

  1. Enter a line of string: I have 2 C++ programming books.
  2. Vowels: 8
  3. Consonants: 14
  4. Digits: 1
  5. White spaces: 5