C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ 程序,用于查找字符串中元音、辅音、数字和空格的数量

用于查找字符串中元音、辅音、数字和空格数的 C++ 程序

在本例中,我们将学习找出 C++ 字符串中存在的元音、辅音、数字和空格的数量。
要理解此示例,您应该了解以下C++ 编程 主题:
C++ 数组 C++ 字符串

示例 1: 来自 C 风格的字符串

这个程序从用户那里获取一个 C 风格的字符串并计算元音、辅音、数字和空格的数量。
#include <iostream>
using namespace std;
int main()
{
    char line[150];
    int vowels, consonants, digits, spaces;
    vowels =  consonants = digits = spaces = 0;
    cout << "Enter a line of string: ";
    cin.getline(line, 150);
    for(int i = 0; line[i]!='\0'; ++i)
    {
        if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
           line[i]=='o' || line[i]=='u' || line[i]=='A' ||
           line[i]=='E' || line[i]=='I' || line[i]=='O' ||
           line[i]=='U')
        {
            ++vowels;
        }
        else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
        {
            ++consonants;
        }
        else if(line[i]>='0' && line[i]<='9')
        {
            ++digits;
        }
        else if (line[i]==' ')
        {
            ++spaces;
        }
    }
    cout << "Vowels: " << vowels << endl;
    cout << "Consonants: " << consonants << endl;
    cout << "Digits: " << digits << endl;
    cout << "White spaces: " << spaces << endl;
    return 0;
}
输出
Enter a line of string: this is 1 hell of a book.
Vowels: 7
Consonants: 10
Digits: 1
White spaces: 6

示例 2: 来自字符串对象

这个程序从用户那里获取一个字符串对象并计算元音、辅音、数字和空格的数量。
#include <iostream>
using namespace std;
int main()
{
    string line;
    int vowels, consonants, digits, spaces;
    vowels =  consonants = digits = spaces = 0;
    cout << "Enter a line of string: ";
    getline(cin, line);
    for(int i = 0; i < line.length(); ++i)
    {
        if(line[i]=='a' || line[i]=='e' || line[i]=='i' ||
           line[i]=='o' || line[i]=='u' || line[i]=='A' ||
           line[i]=='E' || line[i]=='I' || line[i]=='O' ||
           line[i]=='U')
        {
            ++vowels;
        }
        else if((line[i]>='a'&& line[i]<='z') || (line[i]>='A'&& line[i]<='Z'))
        {
            ++consonants;
        }
        else if(line[i]>='0' && line[i]<='9')
        {
            ++digits;
        }
        else if (line[i]==' ')
        {
            ++spaces;
        }
    }
    cout << "Vowels: " << vowels << endl;
    cout << "Consonants: " << consonants << endl;
    cout << "Digits: " << digits << endl;
    cout << "White spaces: " << spaces << endl;
    return 0;
}
输出
Enter a line of string: I have 2 C++ programming books.
Vowels: 8
Consonants: 14
Digits: 1
White spaces: 5
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4