2012-10-11 122 views
0

我有兩個包含字符串的向量。我想將vector1的每個字符串與vector2的每個字符串進行比較,並檢查兩個字符串中有多少個單詞相同。比較字符串逐字C++

Compare::Compare(vector<string> text1, vector<string> text2, int ratio) 
{ 
    text1Size_ = text1.size(); 
    text2Size_ = text2.size(); 

    if(text1Size_ > text2Size_) 
    { 
     totalWords_ = text1Size_; 
    } 
    else 
    { 
     totalWords_ = text2Size_; 
    } 

    it = text1.begin(); 

    for(int i = 0; i < text1Size_; i++) 
    { 
     it2 = text2.begin(); 

     for(int i = 0; i < text2Size_; i++) 
     { 
      if(*it == *it2) 
      { 
       cout << "Perfect match"; 
      } 
      it2++; 
     } 
     it++; 
    } 
} 

我需要的,如果他們有類似的話至少比來回報每相似的弦:我的代碼只有當兩個字符串是完全類似的工作。

是否有比解析每個字符串更簡單的方法,將每個單詞放在數組中並比較它們?

-EDIT-

通過詞我的意思是像「鳥」這樣的書面文字。我會舉一個例子。

讓說我只有每個矢量一個字符串,我需要類似的70%的比例:

string1 : The blue bird. 
string2 : The bird. 

我想要做的是檢查是否有書面的話,至少60%匹配兩個句子。

在這裏我有匹配的「The」和「Bird」。所以我有2/3類似的詞(66.666%)。所以這些字符串將被接受。

-edit 2-

我不認爲我可以使用「.compare()」在這裏,因爲它會檢查每一個字符,而不是每一個文字...

+0

您對「單詞」的使用有點令人困惑。你是否想要像8字節(16位)那樣匹配寫入的單詞或計算機單詞?此外,即使它的文字(即「狗」,「貓」,「馬」,我也沒有試圖比較字符串的實際內容,這意味着你必須在談論字符串是否與另一個字符串匹配,方法,所以只是使用這些。 –

+0

是否有沒有使用.compare()的原因? – 2012-10-11 18:05:50

+0

這似乎是http://stackoverflow.com/questions/5492485/strcmp-or-stringcompare?rq=1這聽起來像你應該做更多的研究正確的方式來比較兩個字符串在C++ –

回答

1

使用字符串流將一個字符串分成單詞:

#include <sstream> 

bool is_similar(string str1, string str2) 
{ 
    vector<string> words1, words2; 
    string temp; 

    // Convert the first string to a list of words 
    std::stringstream stringstream1(str1); 
    while (stringstream1 >> temp) 
     words1.push_back(temp); 

    // Convert the second string to a list of words 
    std::stringstream stringstream2(str2); 
    while (stringstream2 >> temp) 
     words2.push_back(temp); 

    int num_of_identical_words = 0; 
    // Now, use the code you already have to count identical words 
    ... 

    double ratio = (double)num_of_identical_words/words2.size(); 
    return ratio > 0.6; 
} 
+0

這工作。非常感謝! – LolCat