2012-03-22 110 views
0

我使用两个字符串向量来存储两个文本文件。我需要将两者进行比较,并将该单词更改为匹配单词的“*”。我已经为所有匹配100%的字符串('蝙蝠'到'蝙蝠')工作,但我需要它也包括战斗,因为它有字符串'蝙蝠'。我试图使用strcmp,但没有运气!如果任何人都可以提供帮助,并尝试指引我朝着正确的方向发展。谢谢。测试列表向量包含所有单词列表,并且输入列表包含原始数据(句子和单词)。比较两个向量字符串的相似性C++

这里是代码:

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

尝试[string :: find()](http://www.cplusplus.com/reference/string/string/find/)。它将在字符串中查找搜索项的任何实例。 – chris 2012-03-22 01:04:50

+0

谢谢。在过去的几个小时里,我一直在拉我的头发! – MacKey 2012-03-22 01:16:28

+0

嗨克里斯,作为新成员,当我点击upvote时,它声明我需要15个声望!不能看我怎么能超越那个! – MacKey 2012-03-22 14:51:04

回答

2

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

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

先生,你是一个天才!像魅力一样工作! :D – MacKey 2012-03-22 01:17:01

+0

@MacKey没问题。 – twain249 2012-03-22 01:17:36

1

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

+0

谢谢。得到它的工作。为什么我之前没有加入这个论坛!充满知识的人:D – MacKey 2012-03-22 01:18:17

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_WORDREPLACE_TERM结果:
*** ***tle Hello

拉姆达可以用普通的函数地址,如果它适合你更好的进行更换。

+0

优秀的细分。大!谢谢 – MacKey 2012-03-22 14:48:49