Blog

  1. Why do the C++ Standard Library does not have a function to lower/upper case a std::string?

    As we know the C++ is one of the old languages (officialy renamed from C with classes to C++ and released during 1983). During all this year this language has been matured very much. But still within all this, this language does not have a simple std::string::tolower() or std::string::toupper() methods for string manuplation.
    I mean even C <string.h> have a char *strlwr(char *str) and char *strupr(char *str) function, now I know what you are gonna say that.

    Why don't you just take a std::string and use the .c_str() method and use strlwr or strupr on it.

    But let me tell you, the value returned by the .c_str() is a const char*, that means you can't mutate the value of the string, sure you can use strcpy and copy the value to another variable, but it will only cause extra overhead.
    So what other ways are left for us?
    1. We can either iterate through the string and use a function called tolower(char c)
    2. We can use std::transform from <algorithm> library to change the case of the string in one go
    Both methods are great, but the first iterative methods is kinda verbose and less used now days.
    The second methods looks like this:
    #include <algorithm>
    int main() {
        std::string sampleLower("this is a lower string");
        std::transform(sampleLower.begin(), sampleLower.end(), sampleLower.begin(), toupper);
        return 0;
    }
    This will output:
    $ THIS IS A LOWER STRING
    The transform takes 4 parameters Now the thing it, that this lowering and capatilization only works ASCII characters, for the unicode characters it might fail, so you will need to use std::wstring for the extra wide enicodes such as é or á, etc.

    Now compared to other language like Python, which have simple str.lower() or str.upper() methods which makes the work easy, but still, C++ is a go to language for writing fast performant systems code.
    The full example can be found here

    References / Citation
    1. https://stackoverflow.com/a/313990/31691327
    2. https://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/
    3. https://en.cppreference.com/w/cpp/algorithm/transform.html