比较两个向量字符串的相似性C++
Comparing two vector strings for similarities C++
我使用两个字符串向量来存储两个文本文件。我需要将两者进行比较,并将匹配单词的单词更改为"*"。我已经为100%匹配的字符串("bat"到"bat")做了所有的工作,但我需要它也包括battle,因为它有字符串"bat"。我试过使用strcmp,但没有成功!如果有人能帮上忙,试着给我指明正确的方向。非常感谢。testlist向量包含所有单词列表,inputlist包含原始数据(句子和单词)。
以下是代码:
for (int j=0; j < testlist.size(); j++)
{
for (int i = 0; i < inputlist.size(); i++)
{
if (inputlist[i] == testlist[j])
{
inputlist[i] ="*";
}
}
}
您可以使用find()
而不是strcmp()
size_t found = inputlist[i].find(testlist[j]);
if(found != string::npos) {
inputlist[i] = "****";
}
似乎,匹配一个单词所需要做的就是查看输入列表中的单词是否包含测试列表中的词。您可以使用例如word.find(contains) != std::string::npos
来检测包含,以查看word
是否包含字符串contains
。
如果要替换包含该术语的每个字符串,或者只替换带有星号的术语,for_each
和string::find
以及string::replace
是一个很好的组合。
#include <iostream>
using std::cout;
#include <vector>
using std::vector;
#include <string>
using std::string;
#include <algorithm> //for_each
#define REPLACE_WORD
int main()
{
vector<string> testlist (3); //your file
testlist [0] = "bat";
testlist [1] = "battle";
testlist [2] = "Hello";
string searchTerm = "bat";
for_each (testlist.begin(), testlist.end(), //iterate through vector
[&](string &word) { //calling this lambda for each
#ifdef REPLACE_WORD //replacing whole word
if (word.find (searchTerm) != string::npos) //if term is found
word.replace (0, word.length(), word.length(), '*'); //replace starting at char 0 for length() chars, with length() *s
#else //REPLACE_TERM
if (word.find (searchTerm) != string::npos)
word.replace (word.find (searchTerm), searchTerm.length(), searchTerm.length(), '*'); //same, but start at where it finds the term, and only replace that
#endif
} //end lambda
); //end for_each
for_each (testlist.begin(), testlist.end(), [](string word){cout << word << ' ';}); //output vector
}
此输出:*** ****** Hello
而将REPLACE_WORD
更改为REPLACE_TERM
会导致:*** ***tle Hello
如果lambda更适合您,可以用普通函数地址替换它。