2012-10-11 120 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