C++的string大小写转换

参考:http://forums.codeguru.com/showthread.php?489969-no-matching-function-transform

这里介绍了 C++ STL string 大小写转换的代码,但是要注意,可能有些机器用下面的代码编译不过

[cpp]view plaincopy

#include  // toupper, tolower

#include 

#include 

#include     // transform

usingnamespacestd;

intmain()

{

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;

return0;

}

可能的错误提示如下:

[plain]view plaincopy

error: no matching function for call to ‘transform(__gnu_cxx::__normal_iterator, std::allocator > >, __gnu_cxx::__normal_iterator, std::allocator > >, __gnu_cxx::__normal_iterator, std::allocator > >, )’

这里说明了原因:

The problem is that the version of std::tolower inherited from the C standard library is a non-template function, but there are other versions of std::tolower that are function templates, and it is possible for them to be included depending on the standard library implementation. You actually want to use the non-template function, but there is ambiguity when just tolower is provided as the predicate.

翻译过来就是说,既有C版本的toupper/tolower函数,又有STL模板函数toupper/tolower,二者存在冲突。

解决办法:

在toupper/tolower前面加::,强制指定是C版本的(这时也不要include 了):

[cpp]view plaincopy

#include 

#include 

#include     // transform

usingnamespacestd;

intmain()

{

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;

return0;

}

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