C++ STL string 大小写转换

代码如下:

#include 
#include 
#include     // transform
using namespace std;
 
int main()
{
   string str = "abcdADcdeFDde!@234";
   transform(str.begin(), str.end(), str.begin(), ::toupper);
   cout << str << endl;
   transform(str.begin(), str.end(), str.begin(), ::tolower);
   cout << str << endl;
   return 0;
}

 但在使用g++编译时会报错:
对 ‘transform(__gnu_cxx::__normal_iterator, std::allocator > >, __gnu_cxx::__normal_iterator, std::allocator > >, __gnu_cxx::__normal_iterator, std::allocator > >, )’ 的调用没有匹配的函数。
    这里出现错误的原因是Linux将toupper实现为一个宏而不是函数:
/usr/lib/syslinux/com32/include/ctype.h:

/* Note: this is decimal, not hex, to avoid accidental promotion to unsigned */  
#define _toupper(__c) ((__c) & ~32)  
#define _tolower(__c) ((__c) | 32)  
__ctype_inline int toupper(int __c)  
{  
return islower(__c) ? _toupper(__c) : __c;  
}  
__ctype_inline int tolower(int __c)  
{  
return isupper(__c) ? _tolower(__c) : __c;  
}  

 两种解决方案:

1.transform(str.begin(), str.end(), str.begin(), (int (*)(int))toupper);

    这里(int (*)(int))toupper是将toupper转换为一个返回值为int,参数只有一个int的函数指针。

2.自己实现ToUpper函数:

int ToUpper(int c)  
{  
    return toupper(c);  
}  
transform(str.begin(), str.end(), str.begin(), ToUpper);  

附:大小写转换函数

#include 
#include 
#include 
using namespace std;
void ToUpperString(string &str)
{
    transform(str.begin(), str.end(), str.begin(), (int (*)(int))toupper);
}
void ToLowerString(string &str)
{
    transform(str.begin(), str.end(), str.begin(), (int (*)(int))tolower);
}

转自:https://blog.csdn.net/areskris/article/details/6977520#

你可能感兴趣的:(C++ STL string 大小写转换)