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

c++
小億
176
2024-07-27 02:35:07

要?jiǎng)h除一個(gè)指定的字符串,可以使用find()函數(shù)找到字符串在原始字符串中的位置,然后使用substr()函數(shù)刪除該字符串。以下是一個(gè)示例代碼:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str = "Hello World";
    string toDelete = "World";

    size_t pos = str.find(toDelete);
    if (pos != string::npos) {
        str.erase(pos, toDelete.length());
    }

    cout << str << endl;

    return 0;
}

上面的代碼中,我們定義了一個(gè)原始字符串str和一個(gè)要?jiǎng)h除的字符串toDelete。然后使用find()函數(shù)找到toDeletestr中的位置,并使用erase()函數(shù)刪除該字符串。最后打印出刪除指定字符串后的結(jié)果。

0