Home > C Programming, C++, VC++, MFC > Functions for converting strings to upper/lower case

Functions for converting strings to upper/lower case

Use following functions

  1. _strupr
  2. _strlwr
  3. std::transform – does the trick too but hard to understand
/* STRLWR.C: This program uses _strlwr and _strupr to create
 * uppercase and lowercase copies of a mixed-case string.
 */

#include <string .h>
#include <stdio .h>

void main( void )
{
   char str[100] = "The String to End All Strings!";
   printf( "Mixed: %s\n", str );
   printf( "Lower: %s\n", _strlwr( str ));
   printf( "Upper: %s\n", _strupr( str ));
}

// Output
// Mixed: The String to End All Strings!
// Lower: the string to end all strings!
// Upper: THE STRING TO END ALL STRINGS!

How about converting std::string to upper or lower case?

// Convert std::string to upper or lower case
std::string teststr = “Nibu Babu Thomas”;
_strlwr( &teststr[0] );
cout << endl << teststr.c_str() << endl; _strupr( &teststr[0] ); cout << teststr.c_str() << endl;[/sourcecode] How about converting 'CString' to upper or lower case? Fortunately and wisely enough there are member functions called 'MakeLower', 'MakeUpper'. Phew! [sourcecode language='cpp']CString csTest = _T( "Nibu Babu Thomas" ); csTest.MakeUpper();// Now in upper case csTest.MakeLower(); // Now in lower case[/sourcecode]

Advertisements
  1. Popescu Radu Alexandru (aka u0m3)
    May 11, 2009 at 3:44 am

    Is the std::transform method more efficient for std::string/std::wstring than _strlwr/_strupr?

    • May 11, 2009 at 9:38 am

      _strlwr/_strupr is more efficient :), but some insist that they don’t want these C API’s. 😉

      • Q
        February 18, 2010 at 1:32 am

        It’s not that we “don’t want it”, it’s that as the APIs are today you can’t guarantee that it’ll work on every compiler/OS/etc. If the C++ standard guaranteed that strupr/strlwr existed and that *(std::string[0]) actually pointed to something writable (or even that std::string::c_str returned a mutable char*), there wouldn’t be a problem. (Of course on MVC++ it’ll all work fine, and if the code doesn’t need to be portable you should feel free to do it the fast way.)

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: