2007年9月16日星期日

(C++) Convert a std::string to upper case

(C++) Convert a std::string to upper case
There are two ways given to convert a std::string to uppercase:

* The for-loop way
* The STL algorithm way

The for-loop way

1. include

//#include // std::toupper

1. include // std::toupper


//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;
}



The STL algorithm way
Using std::transform.

Prefer algorithm calls over hand-written loops [1,2].

1. include
2. include // std::toupper
3. include


int main()
{
// explicit cast needed to resolve ambiguity
std::transform(myString.begin(), myString.end(), myString.begin(),
(int(*)(int)) std::toupper);
}

没有评论: