Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 131,108 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,159 people online right now. Registration is fast and FREE... Join Now!





Convert cases of strings

Two functions, used to convert c++ strings from upper case to lowercase and vice versa. Each takes a string argument, and returns the converted string. Please note that parameters should be validated before passing them to the functions.

Submitted By: Amadeus
Actions:
Rating:
Views: 53,415

Language: C++

Last Modified: February 25, 2005
Instructions: Include either the ctype.h OR cctype libraries, as well as the stdlib.h as part of the preprocessor directives.

Snippet


  1. string StringToUpper(string strToConvert)
  2. {//change each element of the string to upper case
  3.    for(unsigned int i=0;i<strToConvert.length();i++)
  4.    {
  5.       strToConvert[i] = toupper(strToConvert[i]);
  6.    }
  7.    return strToConvert;//return the converted string
  8. }
  9.  
  10. string StringToLower(string strToConvert)
  11. {//change each element of the string to lower case
  12.    for(unsigned int i=0;i<strToConvert.length();i++)
  13.    {
  14.       strToConvert[i] = tolower(strToConvert[i]);
  15.    }
  16.    return strToConvert;//return the converted string
  17. }

Copy & Paste


Comments


jeronimo0d0a 2008-05-07 08:28:38

With most character sets you can set strToConvert -= 'a' - 'A' ; // to lower strToConvert += 'a' - 'A' ; // to upper without the overhead of a function call. I realize that this is less portable, but portability is not an issue for some.

Amadeus 2008-05-07 10:32:21

Very true sir! :) It is, however, an issue for me. Of course, a simple call to the std::transform() algorithm would be just as easy. An example: http://forums.devx.com/showthread.php?t=83058

wartech 2008-08-31 23:20:56

Thanks for the snippet. I used the StringToLower function with ease.


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month