Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ นับสระ พยัญชนะ ตัวเลข และช่องว่างในสตริง


String อาจมีสระ พยัญชนะ ตัวเลข ช่องว่าง โปรแกรมนี้นับจำนวนแต่ละประเภท

ตัวอย่าง: "There are 7 colours in the rainbow" → สระ 12, พยัญชนะ 15, ตัวเลข 1, ช่องว่าง 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 loop วนทุกตัวอักษรจน \0 ตรวจสอบลำดับ:

  1. เป็นสระ (a,e,i,o,u พิมพ์เล็ก/ใหญ่) → vowels++
  2. เป็นตัวอักษร a-z หรือ A-Z → consonants++
  3. เป็นตัวเลข 0-9 → digits++
  4. เป็นช่องว่าง → spaces++
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;
    }
}

แสดงผลลัพธ์ทั้ง 4 ประเภท