[c++] 문자열에서 특정 문자열 치환하는 방법

C++에서는 std::string 클래스를 사용하여 문자열을 다룰 수 있습니다. std::string 클래스는 find()replace()와 같은 멤버 함수를 제공하여 문자열을 찾고 바꿀 수 있습니다.

다음은 특정 문자열을 치환하는 예제 코드입니다.

#include <iostream>
#include <string>

int main() {
    std::string str = "hello world, hello c++";
    std::string oldStr = "hello";
    std::string newStr = "hi";

    size_t pos = 0;

    while ((pos = str.find(oldStr, pos)) != std::string::npos) {
        str.replace(pos, oldStr.length(), newStr);
        pos += newStr.length();
    }

    std::cout << str << std::endl;
    return 0;
}

이 예제 코드는 “hello”를 “hi”로 치환하는 방법을 보여줍니다. find()를 사용하여 기존 문자열을 찾고, replace()를 사용하여 새로운 문자열로 바꿉니다.

이 예제 코드를 실행하면 “hi world, hi c++”이 출력될 것입니다.

더 자세한 내용은 C++ 문자열 치환을 참고하시기 바랍니다.