[c++] 문자열에서 특정 문자열 치환

가끔씩 문자열에서 특정 부분을 다른 문자열로 바꾸는 작업이 필요할 때가 있습니다. C++에서는 여러 가지 방법을 사용하여 문자열에서 원하는 부분을 치환할 수 있습니다.

1. string::replace 함수 사용

string::replace 함수는 기존 문자열에서 지정된 위치의 부분을 새로운 문자열로 대체할 수 있습니다. 예를 들어, 다음과 같이 사용할 수 있습니다.

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    str.replace(7, 5, "C++"); // "World"를 "C++"로 치환
    std::cout << str << std::endl;  // 출력: "Hello, C++!"
    return 0;
}

2. find와 substr을 사용하여 직접 구현

string::find 함수와 string::substr 함수를 사용하여 직접 원하는 문자열을 찾고 치환할 수도 있습니다.

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    size_t pos = str.find("World");
    if (pos != std::string::npos) {
        str = str.substr(0, pos) + "C++" + str.substr(pos + 5);
    }
    std::cout << str << std::endl;  // 출력: "Hello, C++!"
    return 0;
}

3. Regex(정규식) 사용

만약 패턴이 복잡하거나 여러 부분을 한 번에 치환해야 하는 경우 정규식을 사용할 수도 있습니다. C++11부터 정규식 라이브러리가 표준 라이브러리에 포함되어 있습니다.

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

int main() {
    std::string str = "Hello, World!";
    std::regex pattern("World");
    std::string replacement = "C++";
    str = std::regex_replace(str, pattern, replacement);
    std::cout << str << std::endl;  // 출력: "Hello, C++!"
    return 0;
}

이러한 방법들을 사용하여 C++에서 문자열의 일부를 원하는 문자열로 치환할 수 있습니다.

참고 자료