用 C++ 替换字符串的一部分
我们将在本文中了解如何在 C++ 中用另一个字符串替换一个字符串的一部分。在 C++ 中,替换操作非常简单。它有一个名为 string.replace() 的函数。此 replace 函数只替换匹配项的第一个出现部分。为了替换所有出现的部分,我们使用了一个循环。此 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 << "Initial String :" << my_str << endl;
//replace all Hello with welcome
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 << "Final String :" << my_str;
}输出
Initial String :Hello...Here all Hello will be replaced Final String :ABCDE...Here all ABCDE will be replaced
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP