我想将 std::string
转换为小写。我知道 tolower()
函数。然而,在过去我遇到过这个函数的问题,而且它并不理想,因为将它与 std::string
一起使用需要遍历每个字符。
是否有 100% 有效的替代方案?
最佳答案
改编自Not So Frequently Asked Questions :
#include <algorithm>
#include <cctype>
#include <string>
std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(),
[](unsigned char c){ return std::tolower(c); });
如果不遍历每个角色,您真的无法逃脱。否则无法知道字符是小写还是大写。
如果你真的讨厌tolower()
,这是我不建议您使用的专门的仅 ASCII 替代方法:
char asciitolower(char in) {
if (in <= 'Z' && in >= 'A')
return in - ('Z' - 'z');
return in;
}
std::transform(data.begin(), data.end(), data.begin(), asciitolower);
请注意,tolower()
只能进行单字节字符替换,这对许多脚本来说都是不合适的,尤其是在使用像 UTF- 这样的多字节编码时8.
关于c++ - 如何将 std::string 的实例转换为小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33605878/