用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 祝福语驱散霉运的话简短