如何将字符串(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äöü"
Run Code Online (Sandbox Code Playgroud)
角色ÄÖÜ和äöü(就像Ae,Oe,Ue)将无法正确转换.
PS:我不喜欢大开关汗,而且我也知道BOOST能胜任一切,我更喜欢STL解决方案.
提前谢谢
哎呀
您需要以不同的方式应用它:
for(unsigned i=0;i<str.size();i++)
str[i]=std::toupper(str[i],loc);
Run Code Online (Sandbox Code Playgroud)
或者设置全局区域设置
std::locale::global(std::locale("Germany_german"));
Run Code Online (Sandbox Code Playgroud)
然后
std::transform( str.begin(), str.end(), str.begin(), std::toupper );
Run Code Online (Sandbox Code Playgroud)
请参阅:http://www.cplusplus.com/reference/std/locale/tolower/
注1 C toupper与std :: toupper不同,它接收std :: locale作为参数,它char仅用作参数,同时std::toupper适用于char和wchar_t.
注2 std::locale对于德语来说相当破碎,因为它在字符基础上工作,不能将"ß"转换为"SS",但它适用于大多数其他字符......
注3:如果你需要正确的大小写转换,包括处理像"ß"这样的字符,你需要使用像ICU或Boost.Locale这样的好的本地化库.
如果您使用的是 Unix,请参阅/usr/share/locale/可用的语言环境。看起来像你想要的"de_DE.UTF-8"。
但setlocale(LC_ALL, "");应该将程序设置为在系统的区域设置中工作,无论它是什么。
如果我只是像这样设置默认区域设置而不指定德国,那么您的程序对我有用(我修复了一个闭括号)。