如何在 C++ 中從字串中移除特定字元?


本節中,我們將學習如何在 C++ 中的字串中移除一些字元。在 C++ 中,我們可以使用 erase()remove() 函式輕鬆完成此項任務。remove 函式獲取字串的起始和結束地址,以及要移除的字元。

Input: A number string “ABAABACCABA”
Output: “BBCCB”

演算法

Step 1:Take a string
Step 2: Remove each occurrence of a specific character using remove() function
Step 3: Print the result.
Step 4: End

示例程式碼

 線上演示

#include<iostream>
#include<algorithm>

using namespace std;
main() {
   string my_str = "ABAABACCABA";

   cout << "Initial string: " << my_str << endl;

   my_str.erase(remove(my_str.begin(), my_str.end(), 'A'), my_str.end()); //remove A from string
   cout << "Final string: " << my_str;
}

輸出

Initial string: ABAABACCABA
Final string: BBCCB

更新日期:2023 年 9 月 2 日

83K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告