c++ - 逐字比较字符串 C++

标签 c++ string vector compare

<分区>

我有两个包含字符串的 vector 。我想将 vector1 的每个字符串与 vector2 的每个字符串进行比较,并检查两个字符串中有多少单词相同。我的代码只有在两个字符串完全相似时才有效:

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++;
    }
}

如果它们至少具有相似词的比率,我需要返回每个相似的字符串。

有没有比解析每个字符串、将每个单词放入数组并比较它们更简单的方法?

-编辑-

我所说的单词是指像“鸟”这样的书面单词。我举个例子。

假设我每个 vector 只有一个字符串,我需要 70% 的相似度:

string1 : The blue bird.
string2 : The bird.

我想做的是检查两个句子中是否至少有 60% 的书面单词匹配。

这里有匹配的“The”和“Bird”。所以我有 2/3 的相似词 (66.666%)。所以这些字符串将被接受。

-编辑 2-

我不认为我可以在这里使用“.compare()”,因为它会检查每个字符而不是每个书面单词...

最佳答案

使用字符串流将字符串拆分为单词:

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

关于c++ - 逐字比较字符串 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12845658/

相关文章:

c++ - Bison 问题 - Start Symbol 不导出任何句子

c++ - 使用 MQTT 进行文件传输

java - 尝试计算并打印语句 3 个不同时间的总和

c++ - vector 是否不 protected ,不会越界?

c++ - vector 的错误内存分配 C++

C++ 声明一个带有大小函数的二维数组

c++ - 'int [0]' c++ 的初始化程序太多

string - 从 Golang pkg/net/interface_windows.go 了解 bytePtrToString()

c - 字符串数组排序(唯一字符串)

vector - 将Map <Vec <u8>,Vec <u8 >>展平为Vec <u8>,然后将其返回到Map <Vec <u8>,Vec <u8 >>