유용한 정보
C++ String Replace 함수
cosmohoo
2022. 1. 1. 00:47
반응형
1. 헤더 선언
#include <string>
=> string 헤더에 포함된 함수이므로 string헤더를 참조해야 합니다.
2. 사용법
S.replace(시작점, 변환할 갯수, 대체할 문자열);
=> 위와 같이 시작점, 변환할 개수, 대체할 문자열을 대입하여 주어진 String에서 replace함수를 사용할 수 있습니다.
3. 예제
#include <string>
#include <vector>
#include <map>
#include <sstream>
#include <iostream>
#include <queue>
#include <string.h>
#include <memory.h>
using namespace std;
int main()
{
string s("you are the apple of my eye.");
s.replace(0,3,"We");
cout<<s<<'\n';
string s2("you are the apple of my eye.");
s2.replace(s2.find("are"),3, "were" );
cout<<s2<<'\n';
return 0;
}
=> 위의 코드와 같이 예제를 써보고 진행을 해보면 '0'번째 INDEX부터 3개의 숫자를 대치시킬 것이며 "WE"로 대치시킬 것을 알 수 있습니다.
=> 아래의 코드(s2)도 마찬가지입니다. 다만, find함수를 사용해서 "are"의 시작점을 함수로서 반환하였고, 그 이후 대치할 문자의 개수를 써주고, 대치할 문자열 "were"을 대입하였습니다.
=> 아래의 사진은 실제 구동 화면입니다.
반응형