C++ string大小写转换

来源:互联网 发布:淘宝怎么上一千零一夜 编辑:程序博客网 时间:2024/05/24 00:53

连接:http://blog.csdn.net/areskris/article/details/6977520

C++中没有string直接转换大小写的函数,需要自己实现。一般来讲,可以用stl的algorithm实现:

[cpp] view plaincopy
  1. #include <iostream>  
  2. #include <cctype>  
  3. #include <string>  
  4. #include <algorithm>  
  5. using namespace std;  
  6. int main()  
  7. {  
  8.     string s = "ddkfjsldjl";  
  9.     transform(s.begin(), s.end(), s.begin(), toupper);  
  10.     cout<<s<<endl;  
  11.     return 0;  
  12. }  

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

[cpp] view plaincopy
  1. /* Note: this is decimal, not hex, to avoid accidental promotion to unsigned */  
  2. #define _toupper(__c) ((__c) & ~32)  
  3. #define _tolower(__c) ((__c) | 32)  
  4. __ctype_inline int toupper(int __c)  
  5. {  
  6. return islower(__c) ? _toupper(__c) : __c;  
  7. }  
  8. __ctype_inline int tolower(int __c)  
  9. {  
  10. return isupper(__c) ? _tolower(__c) : __c;  
  11. }  

    两种解决方案:

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

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

2.自己实现ToUpper函数:

[cpp] view plaincopy
  1. int ToUpper(int c)  
  2. {  
  3.     return toupper(c);  
  4. }  
  5. transform(str.begin(), str.end(), str.begin(), ToUpper);  

附:大小写转换函数

[cpp] view plaincopy
  1. #include <cctype>  
  2. #include <string>  
  3. #include <algorithm>  
  4. using namespace std;  
  5. void ToUpperString(string &str)  
  6. {  
  7.     transform(str.begin(), str.end(), str.begin(), (int (*)(int))toupper);  
  8. }  
  9. void ToLowerString(string &str)  
  10. {  
  11.     transform(str.begin(), str.end(), str.begin(), (int (*)(int))tolower);  
  12. }  
--EOF--
0 0
原创粉丝点击