본문 바로가기
IT/programming

[C/C++] C++ string replace_all

by 어느해겨울 2022. 3. 23.

replace_all

string find와 replace를 조합하여 replace_all 기능을 구현한다. 역시 기록용으로 정리한다.

 

소스코드

#include <string>

string replace_all(string &_str, const string& _from, const string& _to) {
    size_t start_pos = 0;
    
    while( (start_pos = _str.find(_from, start_pos)) != std::string::npos ) {
        _str.replace(start_pos, _from.length(), _to);
        start_pos += _to.length();
    }
    
    return _str;
}



출처: https://hashcode.co.kr/questions/239/%EC%8A%A4%ED%8A%B8%EB%A7%81%EC%97%90%EC%84%9C-%ED%8A%B9%EC%A0%95-%EB%8B%A8%EC%96%B4-%EA%B5%90%EC%B2%B4%ED%95%98%EA%B8%B0

 

스트링에서 특정 단어 교체하기

string msg1 = "hello, hello, kk, kkkk, rrrr";과 같이 있을 때 hello를 bye로 바꾸고 싶습니다 string.replace()는 제가 원하는 기능은 아니더라고요

hashcode.co.kr

 

댓글