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;
}
函数指针解决
本文介绍了如何在C++中实现字符串的大小写转换。利用标准库中的transform函数结合toupper和tolower函数,可以轻松地将字符串全部转换为大写或小写形式。
2216

被折叠的 条评论
为什么被折叠?



