[c++] 문자열에서 특정 문자열 치환하는 방법
1. std::string
의 replace
함수 사용
std::string
클래스는 replace
함수를 제공하여 특정 위치의 문자열을 치환할 수 있습니다.
예를 들어, 다음과 같이 사용할 수 있습니다.
#include <string>
#include <iostream>
int main() {
std::string str = "Hello, world!";
str.replace(str.find("world"), 5, "everyone");
std::cout << str << std::endl;
return 0;
}
위 코드는 “world”라는 문자열을 “everyone”으로 치환하는 예제입니다.
2. std::regex
를 사용한 치환
C++11부터 정규 표현식을 지원하므로, std::regex
를 사용하여 특정 문자열을 치환할 수 있습니다.
#include <string>
#include <regex>
#include <iostream>
int main() {
std::string str = "Hello, world!";
std::regex pattern("world");
std::string result = std::regex_replace(str, pattern, "everyone");
std::cout << result << std::endl;
return 0;
}
위 코드는 “world”를 “everyone”으로 치환하는 예제입니다.
참고 자료
std::string
replace: cppreference - std::basic_string::replacestd::regex
를 사용한 치환: cppreference - std::regex_replace
이제 위의 방법들을 사용하여 문자열에서 특정 문자열을 치환할 수 있습니다.