c++ - toupper/tolower + 语言环境(德语)

标签 c++

如何将字符串 (wstring) 从小写字符转换为大写字符,反之亦然? 我在网上搜索了一下,发现有一个 STL 函数 std::transform。
但直到现在我还没有想出如何为函数提供正确的语言环境对象,例如“Germany_german”。 请问谁可以帮忙? 我的代码看起来像:

wstring strin = L"ABCÄÖÜabcäöü";
wstring str = strin;
locale loc( "Germany_german" ); // ??? how to apply this ???
std::transform( str.begin(), str.end(), str.begin(), (int(*)(int)tolower );
//result: "abcäöüabcäöü"

字符 ÄÖÜ 和 äöü(类似于 Ae、Oe、Ue)将无法正确转换。

P.S.:我不喜欢大开关 sweat 而且我知道 BOOST 无所不能,我更喜欢 STL 解决方案。

提前致谢
糟糕

最佳答案

您需要以不同的方式应用它:

for(unsigned i=0;i<str.size();i++)
   str[i]=std::toupper(str[i],loc);

或者设置全局语言环境

std::locale::global(std::locale("Germany_german"));

然后

std::transform( str.begin(), str.end(), str.begin(), std::toupper );

参见:http://www.cplusplus.com/reference/std/locale/tolower/

注意 1 C toupper 不同于 std::toupper,std::toupper 接收 std::locale 作为参数,它仅使用 char 作为参数,而 std::toupper 适用于 charwchar_t

注释 2 std::locale 对于德语来说很糟糕,因为它基于字符工作,不能将“ß”转换为“SS”,但它可以工作对于大多数其他角色...

注意 3:如果您需要正确大小写转换,包括处理“ß”等字符,您需要使用良好的本地化库,如 ICU 或 Boost.Locale

关于c++ - toupper/tolower + 语言环境(德语),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2598569/

相关文章:

java - C++从Java角度设置和映射内存管理

c++ - 无锁单写多读者列表实现细节

c++ - ZeroMQ PGM Multicast 不支持来自应用层的回复处理?

c++ - 输入和输出的二维字符数组问题

c++ - Unordered_Map of Maps 还是 Priority_Queues?

c++ - 为什么包含 <map> 会导致在全局命名空间中定义 div 函数?

c++ - 如何在深拷贝中使用构造函数分配内存?

c++ - 如何让 OpenMP 与 #pragma omp 任务一起工作?

C++ 二叉树遍历与函数指针参数

c++ - 如何编写与此汇编代码相同的 C/C++ 代码?