如何将std :: string转换为小写? [英] How to convert std::string to lower case?

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

问题描述

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

推荐答案

http://notfaq.wordpress.com/ 2007/08/04 / cc-convert-string-to-lowerlower-case /

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

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