C++對string進行大小寫轉(zhuǎn)換操作方法
更新時間:2023年02月06日 11:17:24 作者:YAIMZA
這篇文章主要介紹了C++對string進行大小寫轉(zhuǎn)換操作方法,本文通過兩種方法結(jié)合實例代碼給大家介紹的非常詳細,需要的朋友可以參考下
C++對string進行大小寫轉(zhuǎn)換操作方法
方法一:
使用C語言之前的方法,使用函數(shù),進行轉(zhuǎn)換
#include <iostream> #include <string> using namespace std; int main() { string s = "ABCDEFG"; for( int i = 0; i < s.size(); i++ ) { s[i] = tolower(s[i]); } cout<<s<<endl; return 0; }
方法二:
通過STL的transform算法配合的toupper和tolower來實現(xiàn)該功能
#include <iostream> #include <algorithm> #include <string> using namespace std; int main() { string s = "ABCDEFG"; string result; transform(s.begin(),s.end(),s.begin(),::tolower); cout<<s<<endl; return 0; }
補充:C++ string大小寫轉(zhuǎn)換
1、通過單個字符轉(zhuǎn)換,使用C的toupper、tolower函數(shù)實現(xiàn)
#include <iostream> #include <string> #include <algorithm> using namespace std; int main(){ string str = "ancdANDG"; cout << "轉(zhuǎn)換前的字符串: " << str << endl; for(auto &i : str){ i = toupper(i);//i = tolower(i); } cout << "轉(zhuǎn)換后的字符串: " << str << endl; //或者 for(int i = 0;i < str.size();++i){ str[i] = toupper(s[i]);//str[i] = toupper(s[i]); } cout << "轉(zhuǎn)換后的字符串: " << str << endl; return 0; }
2、通過STL的transform實現(xiàn)
#include <iostream> #include <string> #include <algorithm> using namespace std; int main(){ string str = "helloWORLD"; cout << "轉(zhuǎn)換前:" << str << endl; //全部轉(zhuǎn)換為大寫 transform(str.begin(), str.end(), str.begin(), ::toupper); cout << "轉(zhuǎn)換為大寫:" << str << endl; //全部轉(zhuǎn)換為小寫 transform(str.begin(), str.end(), str.begin(), ::tolower); cout << "轉(zhuǎn)換為小寫:" << str << endl; //前五個字符轉(zhuǎn)換為大寫 transform(str.begin(), str.begin()+5, str.begin(), ::toupper); cout << "前五個字符轉(zhuǎn)換為大寫:" << str << endl; //后五個字符轉(zhuǎn)換為大寫 transform(str.begin()+5, str.end(), str.begin()+5, ::toupper); cout << "前五個字符轉(zhuǎn)換為大寫:" << str << endl; return 0; }
到此這篇關(guān)于C++對string進行大小寫轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)C++ string大小寫轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!