How to convert std::string to lower case?

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

    This could be another simple version to convert uppercase to lowercase and vice versa. I used VS2017 community version to compile this source code.

    #include 
    #include 
    using namespace std;
    
    int main()
    {
        std::string _input = "lowercasetouppercase";
    #if 0
        // My idea is to use the ascii value to convert
        char upperA = 'A';
        char lowerA = 'a';
    
        cout << (int)upperA << endl; // ASCII value of 'A' -> 65
        cout << (int)lowerA << endl; // ASCII value of 'a' -> 97
        // 97-65 = 32; // Difference of ASCII value of upper and lower a
    #endif // 0
    
        cout << "Input String = " << _input.c_str() << endl;
        for (int i = 0; i < _input.length(); ++i)
        {
            _input[i] -= 32; // To convert lower to upper
    #if 0
            _input[i] += 32; // To convert upper to lower
    #endif // 0
        }
        cout << "Output String = " << _input.c_str() << endl;
    
        return 0;
    }
    

    Note: if there are special characters then need to be handled using condition check.

提交回复
热议问题