How to convert std::string to lower case?

后端 未结 26 1733
旧时难觅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:24

    Since none of the answers mentioned the upcoming Ranges library, which is available in the standard library since C++20, and currently separately available on GitHub as range-v3, I would like to add a way to perform this conversion using it.

    To modify the string in-place:

    str |= action::transform([](unsigned char c){ return std::tolower(c); });
    

    To generate a new string:

    auto new_string = original_string
        | view::transform([](unsigned char c){ return std::tolower(c); });
    

    (Don't forget to #include and the required Ranges headers.)

    Note: the use of unsigned char as the argument to the lambda is inspired by cppreference, which states:

    Like all other functions from , the behavior of std::tolower is undefined if the argument's value is neither representable as unsigned char nor equal to EOF. To use these functions safely with plain chars (or signed chars), the argument should first be converted to unsigned char:

    char my_tolower(char ch)
    {
        return static_cast(std::tolower(static_cast(ch)));
    }
    

    Similarly, they should not be directly used with standard algorithms when the iterator's value type is char or signed char. Instead, convert the value to unsigned char first:

    std::string str_tolower(std::string s) {
        std::transform(s.begin(), s.end(), s.begin(), 
                    // static_cast(std::tolower)         // wrong
                    // [](int c){ return std::tolower(c); }           // wrong
                    // [](char c){ return std::tolower(c); }          // wrong
                       [](unsigned char c){ return std::tolower(c); } // correct
                      );
        return s;
    }
    

提交回复
热议问题