我这里是建立了一个string数组,想在每个成员中用find查找某一个字符串,后用erase将其删去,但是出现了在某个成员中不存在此字符串的情况,然后错误无法运行。
如果想在一个 string 数组的每个成员中查找并删除一个字符串,可以使用 std::string::find 和 std::string::erase 来实现。但是在某个成员中不存在要查找的字符串的情况下,find 函数会返回 std::string::npos。所以应该先检查 find 函数的返回值是否为 npos,如果是,就不要进行删除操作。
例如可以这样写代码:
#include <iostream>
#include <string>
int main() {
std::string arr[] = {"Hello", "world", "foo", "bar"};
// 查找并删除字符串 "foo"
for (std::string& str : arr) {
std::size_t pos = str.find("foo");
if (pos != std::string::npos) {
str.erase(pos, 3);
}
}
// 输出修改后的数组
for (const std::string& str : arr) {
std::cout << str << '\n';
}
return 0;
}
这样当 find 函数返回 npos 时,就不会执行 erase 操作,这样就可以避免错误了。
仅供参考,望采纳。