溫馨提示×

c++中string怎么刪除指定字符

c++
小億
470
2024-04-12 11:35:02
欄目: 編程語言

在C++中,可以使用erase方法來刪除指定字符。下面是一個示例代碼:

#include <iostream>
#include <string>

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

    size_t pos = 0;
    while ((pos = str.find(charToRemove, pos)) != std::string::npos) {
        str.erase(pos, 1);
    }

    std::cout << "After removing '" << charToRemove << "': " << str << std::endl;

    return 0;
}

在上面的代碼中,我們首先定義了一個字符串str和要刪除的字符charToRemove。然后使用find方法來查找并刪除指定的字符,直到找不到該字符為止。最后輸出刪除指定字符后的結(jié)果。

0