两个字符串相等
Equality of two strings
用最少的代码比较两个字符串,同时忽略以下内容的最简单方法是什么?
"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-world
和hello wolrd
有97%的可能是相同的意思,只是一个连字符和一个拼写错误。
- 从两个字符串中删除空格。
- 删除两个字符串中的连字符。
- 将两个字符串转换为小写。
- 将所有出现的"saint"answers"st."转换为"st"。 比较正常字符串
#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个要求,
- 删除字符串中的所有空格/连字符(或将其替换为字符,例如'')"hello world" --> "helloworld"
- 比较它们忽略大小写。c++ 中不区分大小写的字符串比较
对于最后一个需求,它更复杂。
首先你需要一本字典,它是KV结构的:
"圣"。:"圣人"
"先生。":"先生"
第二次使用boost令牌将字符串分开,并在KV Store中获取
然后将令牌替换为字符串,但这可能会降低性能:
- 两个字符串在 c++ 中不相等
- 在C++的两个字符串中连接以逗号分隔的唯一值
- 将字符串拆分为标记,并将标记拆分为两个单独的数组
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 比较两个字符串后卡在无限循环中
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用XOR查找O(n)-解决方案中的两个字符串是否为变位符
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 如何将两个字符串加在一起,就好像它们是变量一样?
- 我需要帮助在一个类中输入两个字符串并获取其输出
- 这两个C++语句连接字符串有什么区别?
- 两个字符串之间的数学运算
- 使用 SET(C++) 检查两个给定字符串是否是字谜时出现运行时错误
- 有没有办法我可以在 C++ 中使用 if 语句来说明如果一个字符串不是两个名称的 eqal,它会给出一个输出,ATM i
- 如何在 main 函数中输出两个新字符串C++?
- sscanf() 有两个字符串参数
- 我的字符串数组一次打印出前两个字符串
- 两个 c++ 字符串上的异或
- 函数返回两个字符串的第一个常用字符
- 目标是找到两个 c 字符串之间的公共前缀(必须使用特定的函数标头)