C++ 문자열 교체

Jmnote (토론 | 기여)님의 2023년 10월 28일 (토) 11:36 판 (→‎개요)

1 개요

C++ 문자열 교체
#include <iostream>
using namespace std;

void str_replace_once(string& s, string const& search, string const& replace) {
    size_t pos = s.find(search);
    if (pos == string::npos) {
        return;
    }
    s.replace(pos, search.length(), replace);
}

int main() {
    string s = "hello world hello";
    str_replace_once(s, "hello", "yellow");
    cout << s; // yellow world hello
}
#include <iostream>
using namespace std;

void str_replace(string& s, string const& search, string const& replace) {
    string buf;
    size_t pos = 0;
    size_t prevPos;
    buf.reserve(s.size());
    while (true) {
        prevPos = pos;
        pos = s.find(search, pos);
        if (pos == string::npos) {
            break;
        }
        buf.append(s, prevPos, pos - prevPos);
        buf += replace;
        pos += search.size();
    }
    buf.append(s, prevPos, s.size() - prevPos);
    s.swap(buf);
}

int main() {
    string s = "hello world hello";
    str_replace(s, "hello", "yellow");
    cout << s; // yellow world yellow
}

2 같이 보기

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}