2012-03-22 21 views
0

2つの文字列ベクトルを使用して2つのテキストファイルを保存しています。私は両方を比較し、一致する単語の "*"に単語を変更する必要があります。私は100%( 'バット'から 'バット')に一致する文字列のすべてを持っているが、それに文字列「バット」が入っているので、バトルも含める必要がある。私はstrcmpを使用しようとしましたが、運がありませんでした!誰かが助けになることができたら、正しい方向に私を指差してください。ありがとうございました。テストリストベクトルはすべての単語リストを含み、入力リストは生データ(文章および単語)を含む。ここで類似性に関する2つのベクトル文字列の比較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

+0

ありがとうございます。私は最後の数時間以上これを私に髪を引っ張ってきた! – MacKey

+0

こんにちはクリス、私はupvoteをクリックすると、新しいメンバーとして、それは私が15の評判を必要と述べている!私はそれをどのように克服することができますか? – MacKey

答えて

2

あなたが単語に一致するようにする必要があるすべては、内の単語かどうかを確認することです、それは思わ代わりstrcmp()

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

先生、あなたは天才です!チャームのように働いた! :D – MacKey

+0

@MacKey問題ありません。 – twain249

1

find()を使用することができます入力リストには、テストリストの単語が含まれています。あなたは封じ込めを検出することができます。 word.find(contains) != std::string::nposを参照してwordに文字列containsが含まれているかどうかを確認します。

+0

ありがとうございます。それは働いた。なぜ私はこのフォーラムに早く参加しなかったのですか?知識豊富な人々の完全:D – MacKey

1

あなたはstring::replaceとともに、アスタリスク、for_eachstring::findとの用語、または単に用語を含むすべての文字列を置き換えるために探している場合は良い組み合わせです。

#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 
} 

この出力:それはより良いあなたに合った場合ラムダは、通常の関数のアドレスに置き換えることができ
*** ***tle Hello


*** ****** Hello

REPLACE_WORDREPLACE_TERMに結果を変更する一方。

+0

優れた故障。すばらしいです!ありがとうございました – MacKey

関連する問題