C++ string大小写转换
来源:互联网 发布:淘宝怎么上一千零一夜 编辑:程序博客网 时间:2024/05/24 00:53
连接:http://blog.csdn.net/areskris/article/details/6977520
C++中没有string直接转换大小写的函数,需要自己实现。一般来讲,可以用stl的algorithm实现:
- #include <iostream>
- #include <cctype>
- #include <string>
- #include <algorithm>
- using namespace std;
- int main()
- {
- string s = "ddkfjsldjl";
- transform(s.begin(), s.end(), s.begin(), toupper);
- cout<<s<<endl;
- return 0;
- }
但在使用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:
- /* 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 <cctype>
- #include <string>
- #include <algorithm>
- 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);
- }
- C++: string的大小写转换
- C++: string的大小写转换
- C++: string的大小写转换
- C++: string的大小写转换
- C++_char/string 转换成 int/float char大小写转换
- string 大小写转换
- string大小写转换函数
- string大小写转换函数
- C++ string大小写转换
- string的大小写转换
- string 大小写转换
- string大小写转换函数
- string大小写转换
- C++ string大小写转换
- JAVA String 大小写转换
- C++ string大小写转换
- string大小写转换
- C++ string大小写转换
- (一)程序设计的基本知识
- Activity 生命周期
- TDD相关测试框架
- iOS7的statusBar和navigationBar
- iOS7自定义statusbar和navigationbar的若干问题
- C++ string大小写转换
- (二)对象和类型
- "=="和"equal"的区别
- Laravel+apache 报 404
- sql server 2005 32位+64位、企业版+标准版、CD+DVD 下载地址大全
- LeetCode 题解(263) : Find the Celebrity
- win7(windows 7)系统下安装SQL2005(SQL Server 2005)图文教程
- Ember.js 入门指南——组件定义
- xcode插件 - 生成@3x图片对应的@2x和@1x版本--RTImageAssets