溫馨提示×

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

c++
小億
340
2024-07-27 02:35:07
欄目: 編程語言

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

#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;
}

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

1
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女