显示标签为“string”的博文。显示所有博文
显示标签为“string”的博文。显示所有博文

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

2007年7月21日星期六

如何清空字符串

char [10]="hello";
strcpy(ch,"");
printf("%s",ch);
输出确实为空
但用

for(i=0; i<10;>
printf("%c",ch)
结果却为
ello

如何将整个字符串清空?


#include
#include
int main()
{
char str[10]="hello";
puts(str);
printf("\n");
memset(str,0,10);
puts(str);
}