noobtuts

C++ String Lowercase and Uppercase

Foreword

We all know the problem: we are deep into the game development process when we suddenly need to convert our strings to lowercase or uppercase. Sadly we forgot to create an algorithm for that so we need to browse through the first ten pages of Google in order to find a good one. Let's prevent that from happening by implementing a simple and working solution right now.

Implementation of toUpper

At first we will implement the toUpper function. The purpose of this function is to convert all lowercase letters from a String to uppercase Letters.

Example: 'aBc 3' becomes 'ABC 3'. It's important that letters like numbers or spaces won't be converted to anything different.

#include <locale>
std::string toUpper(const std::string& s)
{
    std::string result;

    std::locale loc;
    for (unsigned int i = 0; i < s.length(); ++i)
    {
        result += std::toupper(s.at(i), loc);
    }
   
    return result;
}

We simply use the std::toupper function from the C++ Standard Library and apply it to not just one character but to each character of the string. Couldn't be simpler and couldn't be safer.

Implementation toLower

The toLower function is the exact opposite of toUpper. The purpose of this function is to convert all uppercase letters from a String to lowercase Letters.

Example: 'aBc 3' becomes 'abc 3'. Again it's very important that letters like numbers or spaces won't be converted to anything different.

#include <locale>
std::string of toLower(const std::string& s)
{
    std::string result;

    std::locale loc;
    for (unsigned int i = 0; i < s.length(); ++i)
    {
        result += std::tolower(s.at(i), loc);
    }
   
    return result;
}

Example

std::cout<<toUpper("123Abc"); // gives us 123ABC
std::cout<<toLower("123Abc"); // gives us 123abc

Summary

Two functions that are really nice to have in our library, with (most likely) the simplest implementation that is possible.