用C ++中的另一个字符串替换字符串的一部分

在这里,我们将看到如何在C ++中用另一个字符串替换字符串的一部分。在C ++中,替换非常容易。有一个名为string.replace()的函数。此替换功能仅替换匹配的第一个匹配项。为此,我们使用了循环。此替换函数从要替换的位置获取索引,获取字符串的长度,然后将字符串放置在匹配的字符串的位置。

Input: A string "Hello...Here all Hello will be replaced", and another string to replace "ABCDE"
Output: "ABCDE...Here all ABCDE will be replaced"

算法

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>
using namespace std;
main() {
   int index;
   string my_str = "Hello...Here all Hello will be replaced";
   string sub_str = "ABCDE";
   cout << "初始字符串:" << my_str << endl;
   //用欢迎替换所有Hello-
   while((index = my_str.find("Hello")) != string::npos) {    //for each location where Hello is found
      my_str.replace(index, sub_str.length(), sub_str); //remove and replace from that position
   }
   cout << "最终字符串:" << my_str;
}

输出结果

初始字符串:Hello...Here all Hello will be replaced
最终字符串:ABCDE...Here all ABCDE will be replaced