C++ string大小写转换以及transform,tolower,toupper,用法

C++中没有提供string类型的大小写转换,今天写了一下,方法很多。

当然可以s[i]+32 or s[i]-32

 

#include <iostream>
#include <string>
#include <cctype>
#include <algorithm>

using namespace std;

int main()
{
    string s = "Hello World";
    cout << s << endl;
    transform(s.begin(),s.end(),s.begin(),::toupper);//<span style="font-family:'Times New Roman';">::toupper使用定义在全局空间里的</span>to<span style="font-family:'Times New Roman';">upp<span style="font-family:'Times New Roman';">er</span></span>
    cout << s << endl;
    transform(s.begin(),s.end(),s.begin(),::tolower);//<font face="'Times New Roman'">::t<span style="font-family:'Times New Roman';">olo<span style="font-family:'Times New Roman';">wer<span style="font-family:'Times New Roman';">使用</span></span></span></font><span style="font-family:'Times New Roman';">定义在全局空间里的</span>to<span style="font-family:'Times New Roman';">lower</span>
    cout << s << endl;
    return 0;
}


查阅了资料,toupper和tolower在C++中定义分别在std和cctype中

 

而定义在std中时原型为charT toupper (charT c, const locale& loc);

而transform函数:

作用是:将某操作应用于指定范围的每个元素。

transform函数有两个重载版本:

 

 

transform(first,last,result,op);//first是容器的首迭代器,last为容器的末迭代器,result为存放结果的容器,op为要进行操作的一元函数对象或sturct、class。

 

 

transform(first1,last1,first2,result,binary_op);//first1是第一个容器的首迭代器,last1为第一个容器的末迭代器,first2为第二个容器的首迭代器,result为存放结果的容器,binary_op为要进行操作的二元函数对象或sturct、class

如上,std中toupper的原型为一个二元函数,所以使用std::toupper会报错:unresolved overloaded function

但是可以这样使用:

 

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

int main()
{
    string s = "Hello World";
    cout << s << endl;
    transform(s.begin(),s.end(),s.begin(),(int (*)(int))toupper);
    cout << s << endl;
    transform(s.begin(),s.end(),s.begin(),(int (*)(int))tolower);
    cout << s << endl;
    return 0;
}

函数指针解决
 

 

 

 

  • 12
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值