用 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

更新於: 30-7-2019

5K+ 瀏覽量

職業加速發展

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.