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

C/C++로 문자열의 모음과 자음을 번갈아 배치하기

모음과 자음이 섞여 있는 입력 문자열이 주어졌을 때, 최종 문자열에서 모음과 자음이 번갈아 나타나도록 재배열하는 문제를 살펴보겠습니다. 모음과 자음을 교대로 배치하려면 입력 문자열은 다음 조건 중 하나를 반드시 만족해야 합니다.

  • 모음과 자음의 개수가 같아야 합니다. 예를 들어 문자열 "individual"은 모음 5개와 자음 5개로 이루어져 있습니다.
  • 모음이 더 많다면, 모음 개수에서 자음 개수를 뺀 차이가 정확히 1이어야 합니다. 예를 들어 문자열 "noe"는 모음 2개와 자음 1개로 구성되어 있습니다.
  • 자음이 더 많다면, 자음 개수에서 모음 개수를 뺀 차이가 정확히 1이어야 합니다. 예를 들어 문자열 "objective"는 모음 4개와 자음 5개로 구성되어 있습니다.

알고리즘

1. 모음의 개수를 센다
2. 자음의 개수를 센다
3. 모음과 자음의 개수 차이(또는 그 반대)가 1보다 크면 오류를 반환한다
4. 입력 문자열을 두 부분으로 분리한다:
   a) 첫 번째 문자열에는 모음만 포함한다
   b) 두 번째 문자열에는 자음만 포함한다
5. 자음과 모음의 개수가 같으면, 각 문자열에서 한 글자씩 번갈아 선택하여 최종 문자열을 만든다
6. 모음이 자음보다 많은 경우:
   a) 두 문자열의 길이를 같게 만들기 위해 추가 모음 하나를 최종 문자열에 먼저 넣는다
   b) 각 문자열에서 한 글자씩 번갈아 덧붙여 최종 문자열을 완성한다
7. 자음이 모음보다 많은 경우:
   a) 두 문자열의 길이를 같게 만들기 위해 추가 자음 하나를 최종 문자열에 먼저 넣는다
   b) 각 문자열에서 한 글자씩 번갈아 덧붙여 최종 문자열을 완성한다

예제 코드

#include <iostream>
#include <string>
using namespace std;
bool is_vowel(char ch) {
    if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch =='u') {
        return true;
    }
    return false;
}
string create_final_string(string &s1, string &s2, int start, int end) {
    string final_string;
    for (int i = 0, j = start; j < end; ++i, ++j) {
        final_string = (final_string + s1.at(i)) + s2.at(j);
    }
    return final_string;
}
string create_alternate_string(string &s) {
    int vowel_cnt, consonant_cnt;
    string vowel_str, consonant_str;
    vowel_cnt = consonant_cnt = 0;
    for (char c : s) {
        if (is_vowel(c)) {
            ++vowel_cnt;
            vowel_str += c;
        } else {
            ++consonant_cnt;
            consonant_str += c;
        }
    }
    if (abs(consonant_cnt - vowel_cnt) >= 2) {
        cerr << "String cannot be formed with alternating vowels and cosonants\n";
        exit(1);
    }
    if ((consonant_cnt - vowel_cnt) == 0) {
        return create_final_string(vowel_str, consonant_str, 0, vowel_cnt);
    } else if (vowel_cnt > consonant_cnt) {
        return vowel_str.at(0) + create_final_string(consonant_str,vowel_str, 1, vowel_cnt);
    }
    return consonant_str.at(0) + create_final_string(vowel_str,consonant_str, 1, consonant_cnt);
}
int main() {
    string s1 = "individual";
    string s2 = "noe";
    string s3 = "objective";
    cout << "Input : " << s1 << "\n";
    cout << "Output: " << create_alternate_string(s1) << "\n\n";
    cout << "Input : " << s2 << "\n";
    cout << "Output: " << create_alternate_string(s2) << "\n\n";
    cout << "Input : " << s3 << "\n";
    cout << "Output: " << create_alternate_string(s3) << "\n\n";
}

실행 결과

위 코드를 컴파일하고 실행하면 다음과 같은 결과가 출력됩니다.

Input : individual
Output: inidivudal
Input : noe
Output: one
Input : objective
Output: bojecitev