问题描述
我想将 std :: string
转换为小写。我知道函数 tolower()
,但是在过去我已经有这个函数的问题,它几乎不理想,因为使用一个字符串将需要迭代每个
I want to convert a std::string
to lowercase. I am aware of the function tolower()
, however in the past I have had issues with this function and it is hardly ideal anyway as use with a string would require iterating over each character.
有100%的时间可以使用吗?
Is there an alternative which works 100% of the time?
推荐答案
从:
#include <algorithm>
#include <string>
std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(), ::tolower);
你真的不会离开不迭代每个字符。无法知道字符是小写还是大写。
You're really not going to get away with not iterating through each character. There's no way to know whether the character is lowercase or uppercase otherwise.
如果你真的讨厌tolower(),这里是一个不可移植的替代,我不推荐你使用:
If you really hate tolower(), here's a non-portable alternative that I don't recommend you use:
char easytolower(char in){
if(in<='Z' && in>='A')
return in-('Z'-'z');
return in;
}
std::transform(data.begin(), data.end(), data.begin(), easytolower);
请注意 :: tolower()
只能进行单字节字符替换,这对于许多脚本来说是不合适的,尤其是在使用UTF-8等多字节编码时。
Be aware that ::tolower()
can only do a per-single-byte-character substitution, which is ill-fitting for many scripts, especially if using a multi-byte-encoding like UTF-8.
这篇关于如何将std :: string转换为小写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!