Computer >> 컴퓨터 >  >> 프로그래밍 >> C++

C++ 문자열에서 모음, 자음, 숫자, 공백 개수 구하는 프로그램


문자열(string)은 널 문자('\0')로 끝나는 1차원 문자 배열입니다. 하나의 문자열 안에는 모음, 자음, 숫자, 공백이 다양하게 섞여 있을 수 있으며, 실무에서도 이런 요소들의 개수를 세어야 하는 경우가 종종 있습니다.

예를 들어 다음과 같습니다.

String: There are 7 colours in the rainbow
Vowels: 12
Consonants: 15
Digits: 1
White spaces: 6

아래는 문자열에 포함된 모음, 자음, 숫자, 공백의 개수를 구하는 C++ 프로그램입니다.

예제 코드

#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(공백)라는 네 개의 변수를 사용해 문자열 내 각 요소의 개수를 저장합니다. 먼저 네 변수를 모두 0으로 초기화한 뒤, for 반복문을 이용해 문자열의 첫 번째 문자부터 널 문자('\0')가 나올 때까지 한 글자씩 검사합니다.

검사한 문자가 모음(a, e, i, o, u 또는 대문자 A, E, I, O, U)에 해당하면 vowels 변수를 1 증가시킵니다. 모음이 아니면서 알파벳 범위(a~z, A~Z)에 속한다면 자음이므로 consonants를, 숫자(0~9)라면 digits를, 공백 문자(' ')라면 spaces를 각각 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;
   }
}

반복문이 종료되면 계산된 모음, 자음, 숫자, 공백의 개수를 cout으로 화면에 출력합니다. 출력 결과는 앞서 확인한 것과 동일합니다.

참고: 코드 더 간결하게 작성하기

cctype 헤더의 tolower(), isalpha(), isdigit(), isspace() 함수를 활용하면 대소문자를 일일이 비교하지 않고도 판별할 수 있어 코드를 훨씬 간결하게 만들 수 있습니다.

#include <cctype>
// ...
char c = tolower(str[i]);
if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u') {
   ++vowels;
} else if(isalpha(c)) {
   ++consonants;
} else if(isdigit(c)) {
   ++digits;
} else if(isspace(c)) {
   ++spaces;
}

이처럼 문자열을 한 글자씩 순회하며 조건 분기만 잘 구성하면, 원하는 문자 유형의 개수를 손쉽게 집계할 수 있습니다.