比较 wstring 和忽略大小写
我确信以前有人问过这个问题,但找不到。 是否有任何内置(即使用 std::wstring 的方法或算法)方法来不区分大小写地比较两个 wstring 对象?
I am sure this would have been asked before but couldn't find it. Is there any built in (i.e. either using std::wstring's methods or the algorithms) way to case insensitive comparison the two wstring objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
如果您不介意受 Microsoft 实现的束缚,您可以使用
中定义的此函数,但如果您想要最佳性能/兼容性/功能比,您可能需要考虑 boost库(无论如何,其中一部分是 stl)。 简单的示例(取自对不同问题的不同答案):
If you don't mind being tied to Microsoft implementation you can use this function defined in
<string.h>
But if you want best performance/compatibility/functionality ratio you will probably have to look at boost library (part of it is stl anyway). Simple example (taken from different answer to different question):
使用标准库:
Using the standard library:
您可以使用 std::tolower() 将字符串转换为小写,或使用函数 wcscasecmp 对 c_str() 进行不区分大小写的比较代码>的。
这是一个您也可以直接使用的比较函子:
You can use
std::tolower()
to convert the strings to lowercase or use the functionwcscasecmp
to do a case insensitive compare on thec_str()
's.Here is a comparison functor you can use directly as well:
您可以使用 boost 字符串算法库。 只要您不打算执行正则表达式,它就是一个仅包含标头的库。 所以你可以很容易地做到这一点。
http://www.boost.org/doc/libs/ 1_39_0/doc/html/string_algo.html
You could use the boost string algorithms library. Its a header only library as long as you're not going to do regex. So you can do that very easily.
http://www.boost.org/doc/libs/1_39_0/doc/html/string_algo.html
说的是英语吧?! 不过我会选择我可爱的Boost:)
Talking about English right ?! though I would go with my lovely Boost :)
如果您需要字符串始终进行不区分大小写的比较(当使用运算符 == 或 != 时),那么一个可能的优雅解决方案是重新定义 char_traits::compare 方法。
定义您自己的结构。 示例
然后,定义您自己的不区分大小写的字符串:
If you need that the string will always make case insensitive comparation (when using operators == or !=), then a possible elegant solution is to redefine char_traits::compare method.
Define your own structure. Example
Then, define your own case insensitive string:
您可以使用mismatch() 或lexicographyal_compare()。 这是 Scott Meyers 在 Effecitve STL 第 35 项中建议的。
You can use mismatch() or lexicographical_compare(). This is suggested by Scott Meyers in Effecitve STL, item 35.