Feb 172009

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!

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]

  3 Responses to “Functions for converting strings to upper/lower case”

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

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

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.