C++ std::wstring 不区分大小写的字符串比较
时间: 2024-01-22 16:04:28 浏览: 229
C++标准库中没有直接提供对std::wstring进行不区分大小写的字符串比较的函数。但是你可以使用一些其他方法来实现这个功能。以下是两种常见的方法:
方法一:使用std::locale和std::use_facet
```cpp
#include <iostream>
#include <locale>
#include <string>
bool caseInsensitiveCompare(const std::wstring& str1, const std::wstring& str2) {
std::locale loc;
const std::ctype<wchar_t>& ctype = std::use_facet<std::ctype<wchar_t>>(loc);
std::wstring str1Lower, str2Lower;
str1Lower.resize(str1.size());
str2Lower.resize(str2.size());
ctype.tolower(&str1[0], &str1[0] + str1.size(), &str1Lower[0]);
ctype.tolower(&str2[0], &str2[0] + str2.size(), &str2Lower[0]);
return str1Lower == str2Lower;
}
int main() {
std::wstring str1 = L"Hello";
std::wstring str2 = L"hello";
if (caseInsensitiveCompare(str1, str2)) {
std::cout << "Strings are equal (case-insensitive comparison)." << std::endl;
} else {
std::cout << "Strings are not equal (case-insensitive comparison)." << std::endl;
}
return 0;
}
```
方法二:使用第三方库,如Boost
```cpp
#include <iostream>
#include <boost/algorithm/string.hpp>
int main() {
std::wstring str1 = L"Hello";
std::wstring str2 = L"hello";
if (boost::iequals(str1, str2)) {
std::cout << "Strings are equal (case-insensitive comparison)." << std::endl;
} else {
std::cout << "Strings are not equal (case-insensitive comparison)." << std::endl;
}
return 0;
}
```
阅读全文