Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to all uppercase leters with std::transform

Tags:

c++

stl

I'm using transform algorithm and std::toupper to achieve this, but can this be done in one line, like this ?

transform(s.begin(), s.end(), ostream_iterator<string>(cout, "\n"),std::toupper);

I get error on this, so do I have to make a unary function for this and call it with transform or I can use some adaptors ?

like image 925
Adrian Avatar asked May 11 '11 10:05

Adrian


People also ask

How do you convert an entire string to uppercase?

The toUpperCase() method converts a string to upper case letters.

How do I convert a string to all uppercase in C++?

C++ String has got built-in toupper() function to convert the input String to Uppercase.

Which function will convert a string to all uppercase?

The strtoupper() function converts a string to uppercase.

How do you change lowercase letters to uppercase in C++?

If lowercase, convert it to uppercase using toupper() function, if uppercase, convert it to lowercase using tolower() function.


1 Answers

Use ostream_iterator<char> instead of ostream_iterator<string>:

transform(s.begin(),s.end(),ostream_iterator<char>(cout,"\n"),std::toupper);

std::transform transforms each character and pass it to the output iterator. That is why the type argument of the output iterator should be char instead of std::string.

By the way, each character will be printed on a newline. Is that what you want? If not, don't pass "\n".

--

Note : You may have to use ::toupper instead of std::toupper.

See these

  • http://www.ideone.com/x6FB5 (each character on a newline)
  • http://www.ideone.com/RcEKn (all characters on the same line)
like image 82
Nawaz Avatar answered Sep 20 '22 08:09

Nawaz