我是 C++ 的新手,在任何帖子中都找不到解决方案。
我有一个 vector
的 string
并且我希望从这个 vector
中删除一个 string
如果它包含以下任意符号:{'.', '%', '&','(',')', '!', '-', '{', '}'}
.
我知道find()
,它只需要一个字符来搜索;但是,我想遍历字符串 vector 中的每个单词,如果它们包含这些字符中的任何一个,则将其删除。例如。 find('.')
还不够。
我尝试了多种途径,例如创建一个包含所有这些字符的 char
vector ,并将每个字符作为 find()
参数进行循环。然而,这个逻辑是非常有缺陷的,因为如果 vector 只有一行带有'.',它会导致中止陷阱。在其中,或者留下一些字符串,其中包含不需要的字符。
vector<std::string> lines = {"hello..","Hello...", "hi%", "world","World!"}
vector<char> c = {'.', '%', '&','(',')', '!', '-', '{', '}'};
for (int i=0; i < lines.size(); i++){
for(int j=0; j < c.size(); j++){
if (lines.at(i).find(c.at(j)) != string::npos ){
lines.erase(lines.begin() + i);
}
}
}
我还在 vector “线”循环中尝试了 find_first_of()
,它产生的结果与上面的代码相同。
if (lines.at(i).find_first_of(".%&()!-{}") != string::npos ){
lines.erase(lines.begin() + i);
有人可以帮我解决这个逻辑吗?
编辑:
当我在删除该行后输入 --i
时,没有显示任何内容并且我有一个中止陷阱,因为它在 vector 范围之外循环。
最佳答案
您的代码中有两个问题,当找到匹配项时,都在内部 for
循环的“内部”。
首先,您不断检查相同 vector 元素以进行(进一步)匹配,即使在您删除它之后也是如此;要解决此问题,请在 if
block 内添加一个 break;
语句,以防止在找到匹配项和 erase()
已调用。
其次,当您确实删除一个元素时,您需要递减i
索引(它将在下一个外循环开始之前递增),这样您不会跳过对 i
将在删除后 编制索引的元素的检查。
这是您的代码的固定版本:
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string> lines = { "hello..", "Hello...", "hi%", "world", "World!" };
std::vector<char> c = { '.', '%', '&','(',')', '!', '-', '{', '}' };
for (size_t i = 0; i < lines.size(); i++) {
for (size_t j = 0; j < c.size(); j++) {
if (lines.at(i).find(c.at(j)) != std::string::npos) {
lines.erase(lines.begin() + static_cast<ptrdiff_t>(i));
i--; // Decrement the i index to avoid skipping next string
break; // Need to break out of inner loop as "i" is now wrong!
}
}
}
for (auto l : lines) {
std::cout << l << std::endl;
}
return 0;
}
但是,正如其他答案中所指出的,您可以通过更多地使用标准库提供的函数来显着改进代码。
关于c++ - 如果字符串包含集合中的任何字符,如何删除它 [c++],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73273817/