[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppToUpperCase
Prefer algorithm calls over hand-written loops [1,2].
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppToUpperCase
(C++) Convert a std::string to upper case
There are two ways given to convert a std::string to uppercase:The for-loop way
//#include <cstdlib> // std::toupper
- include <string>
//Indeed, myString needs to be a copy of the original string std::string StringToUpper(std::string myString) { const int length = myString.length(); for(int i=0; i!=length ; ++i) { myString[i] = std::toupper(myString[i]); } return myString; }
- include <cctype> // std::toupper
The STL algorithm way
Using std::transform.Prefer algorithm calls over hand-written loops [1,2].
int main() { // explicit cast needed to resolve ambiguity std::transform(myString.begin(), myString.end(), myString.begin(), (int(*)(int)) std::toupper); }
- include <algorithm>
- include <cctype> // std::toupper
- include <string>
Other code snippets
Code links
- #include
- algorithm (header file)
- cctype (header file)
- include
- int
- main
- string
- string (header file)
- std
- std::transform
References
- 1) Bjarne Stroustrup. The C++ Programming Language (3rd edition).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'
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
