c++中ignore特定字符串的方法

c++
小樊
81
2024-09-25 03:22:12

在C++中,如果你想忽略特定的字符串,可以使用std::string::find()函數(shù)來(lái)查找字符串中是否包含該特定字符串,然后使用std::string::erase()函數(shù)來(lái)刪除該特定字符串。

例如,假設(shè)你有以下字符串:

std::string str = "Hello, world!";
std::string ignore = "world";

你可以使用以下代碼來(lái)刪除ignore字符串:

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

在上面的代碼中,str.find(ignore)函數(shù)會(huì)在str字符串中查找ignore字符串的位置,如果找到了,則返回該位置的索引值,否則返回std::string::npos。

然后,str.erase()函數(shù)會(huì)從str字符串中刪除ignore字符串,刪除的起始位置為pos,刪除的長(zhǎng)度為ignore.length()。

0