用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
热门推荐
10 钢琴人祝福语女生简短
11 岗位考试顺利祝福语简短
12 关于老师蛋糕祝福语简短
13 娘家妈妈新婚祝福语简短
14 生日留言简短祝福语大全
15 祝福语诗意文案简短
16 校长退休文案祝福语简短
17 宝子生日祝福语简短
18 寒露祝福语毕业寄语简短