C++
[C++] string::replace로 문자열 치환하기
슥지니
2023. 4. 22. 10:00
반응형
1. 특정 문자열 하나를 다른 문자열로 치환하기
#include<iostream>
#include<string>
using namespace std;
int main() {
string s = "hello, world";
string prev = "world"; // 특정 문자열
string next = "hello"; // 다른 문자열
//find : 문자열을 못 찾으면 string::npos 값을 리턴, 찾으면 찾은 문자열의 시작 인덱스 리턴
//replace(특정 문자열의 시작 인덱스, 특정 문자열의 길이, 다른 문자열)
if (s.find(prev) != string::npos) {
s.replace(s.find(prev), prev.length(), next);
}
cout << s; // hello, hello
return 0;
}
2. 특정 문자열 모두를 다른 문자열로 치환하기
#include<iostream>
#include<string>
using namespace std;
int main() {
string s = "hello, world, world, world";
string prev = "world"; // 특정 문자열
string next = "hello"; // 다른 문자열
//find : 문자열을 못 찾으면 string::npos 값을 리턴, 찾으면 찾은 문자열의 시작 인덱스 리턴
//replace(특정 문자열의 시작 인덱스, 특정 문자열의 길이, 다른 문자열)
while (s.find(prev) != string::npos) {
s.replace(s.find(prev), prev.length(), next);
}
cout << s; //hello, hello, hello, hello
return 0;
}
반응형