如何将 std::string 的实例转换为小写 [英] How to convert an instance of std::string to lower case

查看:104
本文介绍了如何将 std::string 的实例转换为小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 std::string 转换为小写.我知道函数 tolower().但是,在过去我遇到过这个函数的问题,无论如何它都不太理想,因为将它与 std::string 一起使用需要迭代每个字符.

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 using it with a std::string would require iterating over each character.

有没有一种替代方法可以 100% 的时间有效?

Is there an alternative which works 100% of the time?

推荐答案

改编自 不那么常见的问题:

#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); });

如果不遍历每个角色,您真的不会逃脱.否则无法知道字符是小写还是大写.

You're really not going to get away without iterating through each character. There's no way to know whether the character is lowercase or uppercase otherwise.

如果你真的讨厌tolower(),这里有一个专门的 ASCII 替代方案,我不建议您使用:

If you really hate tolower(), here's a specialized ASCII-only alternative that I don't recommend you use:

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.

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 的实例转换为小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆