2015-12-15 65 views
0

我有一个字符串向量,我想从类似于字符串的向量中返回一个字符串。例如,向量包含:“load”,“fox”,“google”,“firefox”,字符串是:“mozilla firefox”。此示例中的真实结果是“firefox”。在C++中查找向量中的字符串

我使用下面的代码,但它是错误的,并返回我的示例“狐狸”。

vector<string>::const_iterator it_found = find_if(MyVector.begin(), MyVector.end(), [&MyString](string s) -> bool 
{ return(MyString.find(s) != string::npos); }); 

if(it_found != MyVector.end()) 
{ 
    //Do Somthing 
} 

我该怎么办?

+1

您只检查'vector中的字符串'是否为搜索字符串的一部分。所以你的条件不够具体 – Zaiborg

+2

“'fox”'和''firefox“'在''mozilla firefox”'中。你需要额外的标准来选择'“firefox”'而忽略'“fox”'。 –

回答

3

您正在返回第一个字符串,它是您的搜索字词的子字符串。看来你想要最好的匹配,所以需要更复杂的方法。您可以计算出一些得分,并找到能够给出最高得分的元素,例如与std::max_element

得分可能只是匹配的子字符串的长度或更复杂的东西,如果您稍后改进您的匹配算法。

1

您可以使用此实现split将空白字符分割为输入字符串,并返回std::vector<std::string>

std::vector<std::string> split(std::string const &input) { 
    std::istringstream buffer(input); 
    std::vector<std::string> ret((std::istream_iterator<std::string>(buffer)), 
           std::istream_iterator<std::string>()); 
    return ret; 
} 

然后,每串MyVector与来自split返回矢量候选人进行比较。

std::string MyString = "mozzilla firefox"; 
std::vector<std::string> MyVector = {"fire", "fox", "firefox", "mozilla"}; 
auto candidates = split(MyString); 
auto it_found = std::find_if(MyVector.begin(), MyVector.end(), [&candidates](std::string s) -> bool{ 
    return (std::find(candidates.begin(), candidates.end(), s) != candidates.end()); 
}); 

if(it_found != MyVector.end()){ 
    std::cout<<"\nFound : "<<*it_found; 
} 

输出:

Found : firefox 

注意,这只能找到字符串的第一场比赛中MyVector与在candidates的字符串。