[c++] 정규 표현식을 사용한 대소문자 변환

대소문자 변환은 자주 사용되는 문자열 처리 작업 중 하나입니다. C++에서는 이를 처리하기 위해 정규 표현식을 사용할 수 있습니다. 정규 표현식은 문자열 내의 패턴을 찾거나 대체하는 데 유용한 도구입니다.

regex 라이브러리 사용하기

C++에서 정규 표현식을 사용하기 위해서는 <regex> 라이브러리를 포함해야 합니다. 이 라이브러리를 활용하여 특정 패턴을 찾아 대/소문자로 변환할 수 있습니다.

#include <iostream>
#include <string>
#include <regex>

std::string convertCaseWithRegex(const std::string& input, bool toLower) {
    std::regex pattern("[a-zA-Z]");
    std::string result = input;

    for (std::sregex_iterator it(input.begin(), input.end(), pattern), end; it != end; ++it) {
        std::smatch match = *it;
        if (toLower) {
            result[match.position()] = std::tolower(match.str()[0]);
        } else {
            result[match.position()] = std::toupper(match.str()[0]);
        }
    }

    return result;
}

int main() {
    std::string input = "Hello World";
    std::string lowerCase = convertCaseWithRegex(input, true);
    std::string upperCase = convertCaseWithRegex(input, false);

    std::cout << "Original: " << input << std::endl;
    std::cout << "Lowercase: " << lowerCase << std::endl;
    std::cout << "Uppercase: " << upperCase << std::endl;

    return 0;
}

이 코드는 convertCaseWithRegex 함수를 통해 입력 문자열에서 알파벳 문자를 대/소문자로 변환합니다. 이를 통해 대소문자 변경의 규칙을 유연하게 지정할 수 있습니다.

결론

C++의 정규 표현식을 사용하면 문자열 내의 패턴을 찾고 원하는 대소문자 형식으로 쉽게 변환할 수 있습니다. 이를 통해 대소문자 변환 작업을 간편하게 처리할 수 있습니다.

더 자세한 내용은 cplusplus.com의 정규 표현식 문서를 참고할 수 있습니다.