How to convert std::string to lower case?

2018-12-31 04:35发布

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

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

21条回答
春风洒进眼中
2楼-- · 2018-12-31 05:30
//You can really just write one on the fly whenever you need one.
#include <string>
void _lower_case(std::string& s){
for(unsigned short l = s.size();l;s[--l]|=(1<<5));
}
//Here is an example.
//http://ideone.com/mw2eDK
查看更多
只若初见
3楼-- · 2018-12-31 05:31

Use fplus::to_lower_case().

(fplus: https://github.com/Dobiasd/FunctionalPlus.

Search 'to_lower_case' in http://www.editgym.com/fplus-api-search/)

fplus::to_lower_case(std::string("ABC")) == std::string("abc");
查看更多
深知你不懂我心
4楼-- · 2018-12-31 05:32

From this:

#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 iterating through each character. There's no way to know whether the character is lowercase or uppercase otherwise.

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

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.

查看更多
登录 后发表回答