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;
}

函數指針解決
 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章