比较两个矢量字符串的相似性C ++

时间:2012-03-22 01:01:04

标签: c++ arrays string vector

我正在使用两个字符串向量来存储两个文本文件。我需要比较两者并将单词更改为匹配单词的“ * ”。我已经完成了所有那些匹配100%('bat'到'bat')的字符串,但是我需要它还包括战斗,因为它有字符串'bat'。我曾尝试使用strcmp,但没有运气!如果有人可以提供帮助,请尝试指出我正确的方向。谢谢。 testlist矢量包含所有单词列表,输入列表包含原始数据(句子和单词)。

以下是代码:

for (int j=0; j < testlist.size(); j++)
{
    for (int i = 0; i < inputlist.size(); i++)
    {
        if (inputlist[i] == testlist[j])
        {
            inputlist[i] ="*";
        }
    }
}

3 个答案:

答案 0 :(得分:2)

您可以使用find()代替strcmp()

size_t found = inputlist[i].find(testlist[j]);
if(found != string::npos) {
   inputlist[i] = "****";
}

答案 1 :(得分:1)

看来,匹配单词所需要做的就是查看输入列表中的单词是否包含测试列表中的单词。您可以使用例如word.find(contains) != std::string::npos查看word是否包含字符串contains

答案 2 :(得分:1)

如果您要替换包含该字词的每个字符串,或者仅使用带星号的字词,for_eachstring::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可以更好地适合你,可以用普通的函数地址替换。

相关问题