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

조회수 32182회

string msg1 = "hello, hello, kk, kkkk, rrrr";

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

1 답변

  • 좋아요

    0

    싫어요
    채택 취소하기

    1. boost 사용

    #include <boost/algorithm/string/replace.hpp>
    
    // 원본 스트링을 바꾸는 경우
    std::string in_place = "blah#blah";
    boost::replace_all(in_place, "#", "@");
    
    // 원본 스트링을 바꾸지 않고 다른 스트링에 저장하는 경우
    const std::string input = "blah#blah";
    std::string output = boost::replace_all_copy(input, "#", "@");
    

    2. string::find() 사용

    std::string ReplaceAll(std::string &str, const std::string& from, const std::string& to){
        size_t start_pos = 0; //string처음부터 검사
        while((start_pos = str.find(from, start_pos)) != std::string::npos)  //from을 찾을 수 없을 때까지
        {
            str.replace(start_pos, from.length(), to);
            start_pos += to.length(); // 중복검사를 피하고 from.length() > to.length()인 경우를 위해서
        }
        return str;
    }
    
    ...
    
    std::cout << ReplaceAll(string("Number Of Beans"), std::string(" "), std::string("_")) << std::endl;
    std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("X")) << std::endl;
    std::cout << ReplaceAll(string("ghghjghugtghty"), std::string("gh"), std::string("h")) << std::endl;
    

    결과)

    Number_Of_Beans
    XXjXugtXty
    hhjhugthty
    

    3. 번외 - 철자 하나만 바꾸는 경우 - <algorithm>replace()

    #include <algorithm>
    #include <string>
    
    int main() {
        std::string s = "example string";
        char from = 'e';
        char to = '!';
        std::replace( s.begin(), s.end(), from, to); // replace all 'x' to 'y'
        std::cout << s << endl;
    }
    

    결과)

    !xampl! string
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)