Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

하위 문자열을 다른 하위 문자열로 바꾸기 C++

<시간/>

여기에서 부분 문자열을 다른 부분 문자열로 바꾸는 방법을 볼 것입니다. pos 문자에서 시작하여 len 문자에 걸쳐 있는 문자열 부분을 대체합니다.

바꾸기 함수의 구조는 다음과 같습니다.

string& replace (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen);

매개변수는 pos입니다. :삽입점 str입니다. :string 객체, len :지울 문자의 개수에 대한 정보를 담고 있다.

알고리즘

Step 1: Get the main string, and the string which will be replaced. And the match string
Step 2: While the match string is present in the main string:
Step 2.1: Replace it with the given string.
Step 3: Return the modified string

예시 코드

#include <iostream>
#include <string>
using namespace std;
int main () {
   string base = "this is a test string.";
   string str2 = "n example";
   string str3 = "sample phrase";
   string str4 = "useful.";
   string str = base;
   str.replace(9,5,str2);
   str.replace(19,6,str3,7,6);
   str.replace(8,10,"just a");
   str.replace(8,6,"a shorty",7);
   str.replace(22,1,3,'!');
   str.replace(str.begin(),str.end()-3,str3);
   str.replace(str.begin(),str.begin()+6,"replace");
   str.replace(str.begin()+8,str.begin()+14,"is coolness",7);
   str.replace(str.begin()+12,str.end()-4,4,'o');
   str.replace(str.begin()+11,str.end(),str4.begin(),str4.end());
   cout << str << '\n';
   return 0;
}

출력

replace is useful.