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

[sourcecode language=’cpp’]/* STRLWR.C: This program uses _strlwr and _strupr to create
 * uppercase and lowercase copies of a mixed-case string.


void main( void )
char str[100] = “The String to End All Strings!”;
printf( “Mixed: %sn”, str );
printf( “Lower: %sn”, _strlwr( str ));
printf( “Upper: %sn”, _strupr( str ));

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

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

[sourcecode language=’cpp’]// 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]

3 thoughts on “Functions for converting strings to upper/lower case

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

      • 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.)

Appreciate your comments...