Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Advanced
Jul 17, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Transforming a String to Uppercase Letters

To change the case of all the letters in a string object, use the std::transform() algorithm. This algorithm is defined in the standard header <algorithm>. It takes four arguments. The first two arguments are input iterators that mark the beginning and the end of the string, respectively. The third argument is an output iterator which points to the beginning of the original string (the uppercase version of the string is written the original string). The fourth argument is a unary operator (i.e., an object that supports the () operator and takes one argument). The trick is that transform() applies the unary operator to manipulate every element in the sequence. This unary operator can be a pointer to a function or an object function. In our example, we pass the address of the standard function toupper() that is defined in the standard header <cctype>:

#include <algorithm> 
#include <string> 
#include <iostream> 
#include <cctype>  // for toupper()

int main()
 std::string s("hello"); // lowercase
 // transform the string to uppercase
 std::transform(s.begin(), // original string's beginning
                s.end(), // original string's end
                s.begin(), // where to write the new string?
                toupper); // unary operator

 std::cout << s; // display "HELLO"

Alas, the program above will not compile because the name 'toupper' is ambiguous: there are two functions with this name:

1) int std::toupper(int); // from <cctype>

2) template <class charT> 
  charT std::toupper(charT, const locale&); // from <locale>

We want the first function to be called. To resolve the ambiguity, we add an explicit cast:

std::transform(s.begin(), s.end(), s2.begin(), 
               static_cast < int(*)(int) > (toupper));

This tells the compiler which version of toupper() to choose, namely the one declared in <cctype>. In a similar vein, you can transform a string to lowercase letters by using the tolower() function.

Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date