[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppToUpperCase

(C++) Convert a std::string to upper case

There are two ways given to convert a std::string to uppercase:

The for-loop way

  1. include <string>
//#include <cstdlib> // std::toupper
  1. include <cctype> // std::toupper
//Indeed, myString needs to be a copy of the original string std::string StringToUpper(std::string myString) { const int length = myString.length(); for(int i=0; i!=length ; ++i) { myString[i] = std::toupper(myString[i]); } return myString; }


The STL algorithm way

Using std::transform.

Prefer algorithm calls over hand-written loops [1,2].

  1. include <algorithm>
  2. include <cctype> // std::toupper
  3. include <string>
int main() { // explicit cast needed to resolve ambiguity std::transform(myString.begin(), myString.end(), myString.begin(), (int(*)(int)) std::toupper); }


Other code snippets

Code links

References



last edited (February 15, 2007) by bilderbikkel, Number of views: 13752, Current Rev: 11 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.