溫馨提示×

c++ string如何刪除指定字符

c++
小億
82
2024-09-05 10:02:40
欄目: 編程語言

在 C++ 中,您可以使用 eraseremove 函數(shù)來刪除 std::string 中的指定字符

#include<iostream>
#include<algorithm>
#include<string>

int main() {
    std::string str = "Hello, World!";
    char charToRemove = ',';

    // 使用 remove 函數(shù)移除指定字符
    str.erase(std::remove(str.begin(), str.end(), charToRemove), str.end());

    std::cout << "String after removing '"<< charToRemove << "': "<< str<< std::endl;

    return 0;
}

在這個示例中,我們從字符串 “Hello, World!” 中刪除了逗號。運行此代碼將輸出:

String after removing ',': Hello World!

請注意,std::remove 只是將不需要刪除的字符移到字符串的前面,并返回一個迭代器,指向新的邏輯結尾。然后,erase 函數(shù)用于實際刪除多余的字符。

0