devxlogo

Transforming a String to Uppercase Letters

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 . 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 :

 #include  #include  #include  #include   // 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 2) template    charT std::toupper(charT, const locale&); // from 

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 . In a similar vein, you can transform a string to lowercase letters by using the tolower() function.

See also  How to Avoid Money Transfer Scams  
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist