标准C、C++中字符串的大小写转换方法
(2014-05-27 22:34:43)
标签:
文化 |
From :
如何将一个字符串转换成大写或者小写?这是字符串匹配中经常需要做的事情,然而C++的Standard Library并没有提供将std::string转成大写和小写的功能,只有在提供将char转成大写(toupper)和小写(tolower)的功能而已。
[plain] view
plaincopy
-
#include
-
#include
-
-
int
main() -
{
-
char s[]="This is a TEST string."; -
int i = -1; -
while(s[i++]) -
s[i] = toupper(s[i]); -
//s[i] = tolower(s[i]); -
puts(s); -
-
return 0; -
}
[cpp] view
plaincopy
-
#include
-
#include
-
#include
-
#include
-
-
using
namespace std; -
-
int
main( void) -
{
-
string s="This is ;a TEST stinrg." -
//original -
cout << "orig:" << s << endl; -
-
// to lower case -
transform(s.begin(),s.end(),s.begin(),::tolower); -
cout << "lower:" << s << endl; -
-
//to upper case -
transform(s.begin(),s.end(),s.begin(),::toupper); -
cout << "upper:" << s << endl; -
-
return 0; -
}
[cpp] view
plaincopy
-
#include
-
#include
-
#include
-
#include
-
-
using
namespace std; -
-
char
easytolower( charin) -
{
-
if(in<='Z' && 'A')in>= -
return in-( 'Z'-'z'); -
return in; -
}
-
-
char
easytoupper( charin) -
{
-
if(in<='Z' && 'A')in>= -
return in+( 'Z'-'z'); -
return in; -
}
-
-
int
main( void) -
{
-
string s="This is ;a TEST stinrg." -
//original -
cout << "orig:" << s << endl; -
-
// to lower case -
transform(s.begin(),s.end(),s.begin(),easytolower); -
cout << "lower:" << s << endl; -
-
//to upper case -
//transform(s.begin(),s.end(),s.begin(),easytoupper); -
//cout << "upper:" << s << endl; -
-
return 0; -
}