Link to home
Start Free TrialLog in
Avatar of rbolser
rbolser

asked on

Converting to Uppercase in C++

I am trying to find a method or function that converts a string to uppercase. Like the ucase is vb.. Is there a function in c++ and if not, does someone have the code to it.  I will be converting a string that contains 2 charactors only.

Anyhelp would be great!

ASKER CERTIFIED SOLUTION
Avatar of bliesveld
bliesveld

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of neekris
neekris

The above function can also coded like this:

void uCase(char * sPtr)
{
    for(;*sPtr;++sPtr)
            *sPtr = *sPtr >='a'?*sPtr <= 'z'?*sPtr-('a'-'A'):*sPtr:*sPtr;
}

Advantage of this:
1.  If string is very very long this reduces runtime.

Disadvantage:
2. Loss in Clarity.
Using std::transform with std::toupper is imho the most elegant way to do this (since there's no messing with pointers, and since it's also the shortest solution):

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>

using std::string;
using std::cout;
using std::endl;
using std::toupper
using std::transform;


int main ()
{
  string a = "hElLo WoRld";
  transform(a.begin(), a.end(), a.begin(), toupper);
  cout << a << endl;
  return 0;
}
I think Eelis is more correct than the accepted answer