'C++' std::replace

토스트·2025년 4월 26일

'C++' std::string

목록 보기
6/12

replace

1. 문자열을 활용하여 교체 (+ C-style 문자열)

string& replace(size_t pos, size_t len, const string& str);
string& replace(size_t pos, size_t len, const char* s);

: 문자열의 pos 위치에서 len개의 문자를 str(s)로 교체합니다.

string& replace(const_iterator i1, const_iterator i2, const string& str);
string& replace(const_iterator i1, const_iterator i2, const char* s);

: 문자열의 [i1, i2) 범위를 str(s)로 교체합니다.

<예시 코드>

#include <iostream>
#include <string>

using namespace std;

int main() {
	string str = "toast";
	
	str.replace(1, 2, "e");

	cout << str;

	return 0;
}

결과

2. 부분 문자열을 활용하여 교체

string& replace(size_t pos, size_t len, const string& str, size_t subpos, size_t sublen = npos);
// npos 설정은 버전에 따라 다릅니다. sublen을 무조건 지정해야 할 수도 있습니다.

: 문자열의 pos 위치에서 len개의 문자를 str의 subpos 위치에서 sublen개의 문자로 교체합니다.

<예시 코드>

#include <iostream>
#include <string>

using namespace std;

int main() {
	string str1 = "toast";
	string str2 = "rubi";

	str1.replace(1, 2, str2, 0, 2);

	cout << str1;

	return 0;
}

결과

3. C-style 부분 문자열을 활용하여 교체

string& replace(size_t pos, size_t len, const char* s, size_t n);

: 문자열의 pos 위치에서 len개의 문자를 C-style 문자열인 s의 처음부터 n개의 문자까지 복사하여 string 객체로 변환하여 교체합니다.

string& replace(const_iterator i1, const_iterator i2, const char* s, size_t n);

: 문자열의 [i1, i2) 범위를 C-style 문자열인 s의 처음부터 n개의 문자까지 복사하여 string 객체로 변환하여 교체합니다.

<예시 코드>

#include <iostream>
#include <string>

using namespace std;

int main() {
	string str = "toast";

	str.replace(2, 3, "sstream", 2);

	cout << str;

	return 0;
}

결과

4. 채우기를 활용하여 교체

string& replace(size_t pos, size_t len, size_t n, char c);

: 문자열의 pos 위치에서 len개의 문자를 n개의 문자 c로 교체합니다.

string& replace(const_iterator i1, const_iterator i2, size_t n, char c);

: 문자열의 [i1, i2) 범위를 n개의 문자 c로 교체합니다.

<예시 코드>

#include <iostream>
#include <string>

using namespace std;

int main() {
	string str = "toast";

	str.replace(1, 3, 2, 't');

	cout << str;

	return 0;
}

결과

5. 범위를 활용하여 교체

template<class InputIterator>  
string& replace(const_iterator i1, const_iterator i2, InputIterator first, InputIterator last);

: 문자열의 [i1, i2) 범위를 [first, last) 범위의 문자열로 교체합니다.

<예시 코드>

#include <iostream>
#include <string>

using namespace std;

int main() {
	string str1 = "toast";
	string str2 = "hello";
	
	str1.replace(str1.begin() + 1, str1.end(), str2.begin() + 1, str2.end() - 1);

	cout << str1;

	return 0;
}

결과

6. 초기화 목록을 활용하여 교체

string& replace(const_iterator i1, const_iterator i2, initializer_list<char> il);

: 문자열의 [i1, i2) 범위를 il의 각 문자를 동일한 순서의 값으로 교체합니다.

<예시 코드>

#include <iostream>
#include <string>

using namespace std;

int main() {
	string str = "toast";

	str.replace(str.begin() + 1, str.end() - 1, {'i', 'n'});

	cout << str;

	return 0;
}

결과

0개의 댓글