본문 바로가기

C++

C++ 완벽한 replaceAll 구현하기

반응형

C/C++ 는 문자열을 다루긴엔 정말 성가십니다.

심지어는 Java나 Python에도 기본으로 제공하는 대상이되는 문자열을 모두 치환하는 replaceAll api도 없습니다,,

아니, 정확히는 문자열이 아닌, 문자 1개를 교체해 주지만요,,

 

아래처럼 x에 해당하는 모든 문자의 위치를 while로 찾고, 찾은 위치의 문자를 y로 교체 합니다.

#include <iostream>
#include <string>
 
int main()
{
    std::string s = "C**";
    std::string x = "*", y = "+";
 
    size_t pos;
    while ((pos = s.find(x)) != std::string::npos) {
        s.replace(pos, 1, y);
    }
 
    std::cout << s;
 
    return 0;
}

하지만, 이 마저도 교체하려는 문자열 x, y의 길이가 서로 다른 경우, 기존에 있던 문자열의 내용이 뒤엉키게 됩니다.

 

교체하려는 문자열 x, y의 길이가 서로 다른 경우에도 교체가 되게끔 하려면 아래와 같이 구현하면 됩니다.

string replace_all(
    const string &message, 
    const string &pattern, 
    const string &replace
    ) {
    
    string result = message;
    string::size_type pos = 0;
    string::size_type offset = 0;
 
    while ((pos = result.find(pattern, offset)) != string::npos)
    {
        result.replace(result.begin() + pos, result.begin() + pos + pattern.size(), replace);
        offset = pos + replace.size();
    }
 
    return result;
}

find로 함수로 offset 이후 만큼 떨어진 곳으로부터 pattern에 해당되는 위치를 찾고,

찾았다면 replace 시, 다른 문자열을 침범하지 않기위해 딱 pattern의 길이만큼만 교체합니다.

이후, offset을 찾은 위치에서 pattern의 크기만큼 offset을 늘려줍니다.

 

C++는 문자열을 다루기가 상당히 까다롭네요ㅠ

 

위 코드는 아래 포스팅을 참고했습니다.

https://wendys.tistory.com/8

 

반응형

'C++' 카테고리의 다른 글

C++ string tokenizing  (0) 2022.11.20