Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) StrToUpper

 

std::string convert code snippet to convert a std::string to upper case.

 

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

//From http://www.richelbilderbeek.nl/CppStrToUpper.htm
const std::string StrToUpper(std::string s)
{
  std::transform(s.begin(), s.end(), s.begin(),std::ptr_fun<int,int>(std::toupper));
  return s;
}

 

Note that in the C++ Builder IDE std::ptr_fun can be called without its template arguments. When using the G++ 4.4.1 compiler leaving out the template arguments results in the compile error No matching function for call to 'ptr_fun'.

 

 

 

 

 

StrToUpper using a for loop

 

StrToUpper can be implemented using a for loop, but prefer algorithm calls over hand-written loops [1][2]. View Exercise #9: No for-loops for other ways of replacing for-loops by algorithms.

 

#include <cctype>
#include <string>

//From http://www.richelbilderbeek.nl/CppStrToUpper.htm
const std::string StrToUpper(std::string s) //Not the preferred way
{
  const int sz = static_cast<int>(s.size());
  for(int i=0; i!=sz; ++i)
  {
    s[i] = std::toupper(s[i]);
  }
  return s;
}

 

 

 

 

 

References

 

  1. Bjarne Stroustrup. The C++ Programming Language (3rd edition). 1997. ISBN: 0-201-88954-4. Chapter 18.12.1: 'Prefer algorithms to loops.
  2. Scott Meyers. Effective STL. ISBN: 0-201-74962-9. Item 43: 'Prefer algorithm calls over hand-written loops'.

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict