gpt4 book ai didi

c++ - 如何搜索 vector 字符串中的元素?

转载 作者:行者123 更新时间:2023-12-02 09:48:15 24 4
gpt4 key购买 nike

我试图在 vector 字符串中搜索某些单词。
例如,

vector<string> sentences = ["This is a test string","Welcome to C++!"];
string searchString = "This";
我试过了
if (std::find(sentences.begin(), sentences.end(), searchString) != sentences.end()) {
cout << "Found!";
}
else {
cout << "Not Found!";
}
现在这确实有效,但前提是searchString逐字匹配元素。
例如,如果我们设置
string searchString = "This is a test string";
这将返回找到。
如何分别搜索元素?
谢谢!

最佳答案

for(std::string& s  : sentences)
{
if(s.find(searchString) != std::string::npos)
{
//substring found
}
else
{
//substring not found
}
}
这应该在 vector 的每个字符串中寻找一个单词

关于c++ - 如何搜索 vector 字符串中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63012580/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com