2012-03-22 109 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