您的位置:首页 > 其它

将string字符串中的字符转为全部大写或者全部小写

2014-10-20 11:25 288 查看
使用<algorithm.h>中的transform算法。

#include <iostream>
#include <algorithm>

int main() {
std::string s="hello";
std::string out;
std::transform(s.begin(), s.end(), std::back_inserter(out), std::toupper);
std::cout << "hello in upper case: " << out << std::endl;
}

但是直接编译上述的代码,编译器会报错。报错信息为:

no matching function for call to ‘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> > >,
std::back_insert_iterator<std::basic_string
<char, std::char_traits<char>, std::allocator<char> > >,
<unresolved overloaded function type>)’

只要把代码中的std::toupper改为::toupper就好了,原因在于我们在这里要使用在全局定义的toupper。而不是在命名空间std下定义的toupper。本人的观点是toupper是一个函数,现在编译器搞不清到底要调用哪个命名空间下的toupper函数了。这也是为什么错误信息会提示“unresolved
overloaded function type”的原因。

为了帮助编译器解析正确的重载函数,可以对std::toupper做强制类型转换。

(int (*)(int))std::toupper

也就是如下代码:[code]std::transform(s.begin(), s.end(), std::back_inserter(out),(int (*)(int))std::toupper)
在这里我的理解是命名空间下定义的toupper是一个模板类型的函数。而全局空间的toupper是一个形参为int,返回值也为int的函数。在这里强制转换std::toupper也可以帮助编译器找到正确的重载函数。
注意:
1. 要把string里面的字符全部转换为小写,只需要使用tolower就行了。
2. string里面即便有中文字符,也不影响字符转换。比如把“中国,Hi” 转换为“中国,HI”或者“中国,hi”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐