两个字符串相等

Equality of two strings

本文关键字:字符串 两个      更新时间:2023-10-16

用最少的代码比较两个字符串,同时忽略以下内容的最简单方法是什么?

"hello  world" == "hello world"                   // spaces
"hello-world"  == "hello world"                   // hyphens
"Hello World"  == "hello worlD"                   // case
"St pierre"    == "saint pierre" == "St. Pierre"  // word replacement

我确信以前有人这样做过,而且有一些库可以做这种事情,但我不知道。最好是在c++中,但如果有其他语言的短选项,我也想听听。

或者,我也会对任何可以给出匹配百分比的库感兴趣。例如,hello-worldhello wolrd有97%的可能是相同的意思,只是一个连字符和一个拼写错误。

  1. 从两个字符串中删除空格。
  2. 删除两个字符串中的连字符。
  3. 将两个字符串转换为小写。
  4. 将所有出现的"saint"answers"st."转换为"st"。
  5. 比较正常字符串
例如:

#include <cctype>
#include <string>
#include <algorithm>
#include <iostream>
static void remove_spaces_and_hyphens(std::string &s)
{
    s.erase(std::remove_if(s.begin(), s.end(), [](char c) {
                return c == ' ' || c == '-';
            }), s.end());
}
static void convert_to_lower_case(std::string &s)
{
    for (auto &c : s)
        c = std::tolower(c);
}
static void
replace_word(std::string &s, const std::string &from, const std::string &to)
{
    size_t pos = 0;
    while ((pos = s.find(from, pos)) != std::string::npos) {
        s.replace(pos, from.size(), to);
        pos += to.size();
    }
}
static void replace_words(std::string &s)
{
    replace_word(s, "saint", "st");
    replace_word(s, "st.", "st");
}
int main()
{
    // Given two strings:
    std::string s1 = "Hello, Saint   Pierre!";
    std::string s2 = "hELlO,St.PiERRe!";
    // Remove spaces and hyphens.
    remove_spaces_and_hyphens(s1);
    remove_spaces_and_hyphens(s2);
    // Convert to lower case.
    convert_to_lower_case(s1);
    convert_to_lower_case(s2);
    // Replace words...
    replace_words(s1);
    replace_words(s2);
    // Compare.
    std::cout << (s1 == s2 ? "Equal" : "Doesn't look like equal") << std::endl;
}

当然,有一种方法可以更有效地编写此代码,但我建议您从工作开始,只有当它被证明是瓶颈时才对其进行优化。

听起来你可能对"Levenshtein距离"这样的字符串相似算法感兴趣。例如,搜索引擎或编辑也使用类似的算法来提供拼写更正建议。

我不知道任何库,但为了公平起见,如果速度不是问题,您可以逐字符比较并忽略"特殊"字符(分别在文本中移动迭代器)。

对于文本的比较,您可以使用简单的Levenshtein距离

对于空格和连字符,只需替换字符串中的所有空格/连字符并进行比较。对于大小写,将所有文本转换为大写或小写并进行比较。对于单词替换,您需要一个单词字典,其中键是缩写,值是替换单词。您还可以考虑使用Levenshtein距离算法来显示一个短语与另一个短语的相似程度。如果您想知道一个词/短语与另一个词/短语的接近程度的统计概率,您将需要样本数据来进行比较。

QRegExp是你正在寻找的。它不会打印出百分比,但您可以使用一些非常灵巧的方法来比较一个字符串与另一个字符串,并查找一个字符串与另一个字符串的匹配次数。

几乎所有语言都可以使用

正则表达式。我喜欢GSkinner的学习正则表达式的RegEx页面。

http://qt project.org/doc/qt - 4.8 -/- qregexp.html

希望对你有帮助。

对于前3个要求,

  1. 删除字符串中的所有空格/连字符(或将其替换为字符,例如'')"hello world" --> "helloworld"
  2. 比较它们忽略大小写。c++
  3. 中不区分大小写的字符串比较

对于最后一个需求,它更复杂。
首先你需要一本字典,它是KV结构的:
"圣"。:"圣人"
"先生。":"先生"

第二次使用boost令牌将字符串分开,并在KV Store中获取
然后将令牌替换为字符串,但这可能会降低性能:

http://www.boost.org/doc/libs/1_53_0/libs/tokenizer/tokenizer.htm