How to convert std::string to lower case?

后端 未结 26 1689
旧时难觅i
旧时难觅i 2020-11-22 00:01

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

26条回答
  •  广开言路
    2020-11-22 00:36

    Adapted from Not So Frequently Asked Questions:

    #include 
    #include 
    #include 
    
    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.

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

    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.

提交回复
热议问题