在 C++ 中进行不区分大小写的字符串比较而不将字符串转换为全部大写或全部小写的最佳方法是什么?
请说明这些方法是否对 Unicode 友好以及它们的可移植性。
原文由 Adam 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 C++ 中进行不区分大小写的字符串比较而不将字符串转换为全部大写或全部小写的最佳方法是什么?
请说明这些方法是否对 Unicode 友好以及它们的可移植性。
原文由 Adam 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果您不想使用 Boost 库,那么这里是仅使用 C++ 标准 io 标头的解决方案。
#include <iostream>
struct iequal
{
bool operator()(int c1, int c2) const
{
// case insensitive comparison of two characters.
return std::toupper(c1) == std::toupper(c2);
}
};
bool iequals(const std::string& str1, const std::string& str2)
{
// use std::equal() to compare range of characters using the functor above.
return std::equal(str1.begin(), str1.end(), str2.begin(), iequal());
}
int main(void)
{
std::string str_1 = "HELLO";
std::string str_2 = "hello";
if(iequals(str_1,str_2))
{
std::cout<<"String are equal"<<std::endl;
}
else
{
std::cout<<"String are not equal"<<std::endl;
}
return 0;
}
原文由 Haseeb Mir 发布,翻译遵循 CC BY-SA 4.0 许可协议
3 回答2k 阅读✓ 已解决
2 回答3.9k 阅读✓ 已解决
2 回答3.3k 阅读✓ 已解决
1 回答2.7k 阅读✓ 已解决
3 回答3.5k 阅读
1 回答2.7k 阅读✓ 已解决
3 回答525 阅读✓ 已解决
Boost 包括一个方便的算法: