728x90
반응형
728x90
반응형
728x90
반응형

basic_string의 replace 함수로 문자열 치환하기

주어진 문자열에서 특정 문자열을 다른 문자열로 치환하는 함수를 소개합니다.

cpp

/// \brief 주어진 문자열 내에 존재하는 문자열을 다른 문자열로 치환한다.
/// \param text 원본 문자열
/// \param find_token 찾고자 하는 문자열
/// \param replace_token 치환하고자 하는 문자열
void replace(std::string& text, const std::string& find_token, const std::string& replace_token)
{
    size_t i = 0;
    while ((i = text.find(find_token)) != std::string::npos)
        text.replace(i, find_token.size(), replace_token);
}

이 함수는 text에서 find_token을 찾아 replace_token으로 모두 대체합니다.

사용 예시:

cpp

std::string str1 = "hello\tworld\r\n123\n456";
std::string strFind = "\r\n";
std::string strReplace = "";

replace(str1, strFind, strReplace); // str1 내의 "\r\n"이 모두 제거됩니다.

이 예시에서는 str1에 포함된 모든 "\r\n" 문자열이 빈 문자열로 치환되어 제거됩니다.

728x90
반응형

+ Recent posts