c++ - 如何将 std::string 的实例转换为小写

标签 c++ string c++-standard-library tolower

我想将 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/

相关文章:

c++ - 数组:仅将字符串数组的索引传递给 Int 数组的索引以供输出

python - 字符串 split() 的身份怪癖

c++ - 双向关联容器

c++ - Qt:从一个对象发出相同的信号,但参数不同;插槽根据接收到的参数进行区分

c++ - 如何将 C 函数导入到尚未在 C 头文件中声明的 C++ 项目中?

c++ - 许多嵌套回调的优点/缺点?

c++ - 获取字符串中的第 i 个字符时遇到问题

java - 检查回文字符串

c++ - std::stringstream::flush() 应该做任何事情吗?

c++ - 为什么 std::partition 没有异位变体?