panthema / 2007 / 0602-StdString-Upper-Lower

C++ Code Snippet - In-Place and String-Copy Uppercase/Lowercase Conversion of STL Strings

Posted on 2007-06-02 13:22 by Timo Bingmann at Permlink with 2 Comments. Tags: #c++ #code-snippet

This post completes the small C++ function collection of simple STL string manipulations. The following code snippet shows simple locale-unware uppercase and lowercase conversion functions using tolower and toupper. Nothing revolutionary; I'm just misusing this weblog as a code-paste dump for reuseable code.

Sometimes it is better to have a case-insensitive string class. More about ci_string can be found at Guru of the Week (GotW) #29: Case-Insensitive Strings.

#include <string>
#include <cctype>

// functionals for std::transform with correct signature
static inline char string_toupper_functional(char c)
    return std::toupper(c);

static inline char string_tolower_functional(char c)
    return std::tolower(c);

static inline void string_upper_inplace(std::string &str)
    std::transform(str.begin(), str.end(), str.begin(), string_toupper_functional);

static inline void string_lower_inplace(std::string &str)
    std::transform(str.begin(), str.end(), str.begin(), string_tolower_functional);

static inline std::string string_upper(const std::string &str)
    std::string strcopy(str.size(), 0);
    std::transform(str.begin(), str.end(), strcopy.begin(), string_toupper_functional);
    return strcopy;

static inline std::string string_lower(const std::string &str)
    std::string strcopy(str.size(), 0);
    std::transform(str.begin(), str.end(), strcopy.begin(), string_tolower_functional);
    return strcopy;
#include <assert.h>

// Test the functions above
int main()
    // string-copy functions
    assert( string_upper(" aBc ") == " ABC " );
    assert( string_lower(" AbCdEfG ") == " abcdefg " );

    // in-place functions
    std::string str1 = "  aBc  ";
    std::string str2 = "AbCdEfGh ";


    assert( str1 == "  ABC  " );
    assert( str2 == "abcdefgh " );

    return 0;

Comment by fdv1 at 2007-12-19 14:35 UTC

Hi Timo, Thanks for your example of Flex Bison C++ Unless I'm wrong what you provide in this section is already implemeted in : Boost String Algorithms Library cheers François

Comment by Timo at 2007-12-20 14:19 UTC

Yes, this is nothing new or innovative. The Boost.String library is way more flexible and includes many more algorithms. Nevertheless these are the code snippets I copy into programs, when I don't want to include the huge Boost library and just want plain ASCII case-conversions.

Post Comment
E-Mail or Homepage:

URLs (http://...) are displayed, e-mails are hidden and used for Gravatar.

Many common HTML elements are allowed in the text, but no CSS style.