웬디의 기묘한 이야기

글 작성자: WENDYS
반응형


std::string ReplaceAll

STL의 std::string를 이용하여 간단하게 문자열을 치환할 수 있다.

기본적으론 string.replace가 존재하며 해당 기능은 1번만 치환되므로 모든 문자를 치환하려면 추가로 작업을 해주어야 한다.



다음 코드를 보자



#include <string>

std::string replace_all(
    __in const std::string &message, 
    __in const std::string &pattern, 
    __in const std::string &replace
    ) {

    std::string result = message;
    std::string::size_type pos = 0;

    while ((pos = result.find(pattern)) != std::string::npos)
    {
        result.replace(pos, pattern.size(), replace);
    }

    return result;
}


정상으로 보이는데 뭐가 문제일까..??


실제 테스트 해보면 알 수 있듯이 replace 하려는 문자가 pattern 보다 긴 경우 문자열을 덮어씌우는 현상이 발생한다.

ex)

std::string message = "test message";

text = replace_all(message, "test", "wawawa");


text = wawawaessage 가 된다.



이런 문제점때문에 아래와같은 방법으로 문제 해결이 가능하다.



#include <string>

std::string replace_all(
    __in const std::string &message, 
    __in const std::string &pattern, 
    __in const std::string &replace
    ) {
    
    std::string result = message;
    std::string::size_type pos = 0;
    std::string::size_type offset = 0;

    while ((pos = result.find(pattern, offset)) != std::string::npos)
    {
        result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
        offset = pos + replace.size();
    }

    return result;
}


정답이란 없는법이다.


나에게 맞는 방법 좀더 나은방법이 있다면 그게 좋은것이다




반응형