C++對string進(jìn)行大小寫轉(zhuǎn)換操作方法
更新時間:2023年02月06日 11:17:24 作者:YAIMZA
這篇文章主要介紹了C++對string進(jìn)行大小寫轉(zhuǎn)換操作方法,本文通過兩種方法結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下
C++對string進(jìn)行大小寫轉(zhuǎn)換操作方法
方法一:
使用C語言之前的方法,使用函數(shù),進(jìn)行轉(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來實(shí)現(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;
}
補(bǔ)充:C++ string大小寫轉(zhuǎn)換
1、通過單個字符轉(zhuǎn)換,使用C的toupper、tolower函數(shù)實(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實(shí)現(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進(jìn)行大小寫轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)C++ string大小寫轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言聯(lián)合體Union特點(diǎn)及運(yùn)用全面講解教程
這篇文章主要為大家介紹了C語言聯(lián)合體Union特點(diǎn)及運(yùn)用的全面講解教程有需要深度朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2021-10-10
C語言實(shí)現(xiàn)解析csv格式文件的示例代碼
CSV,有時也稱為字符分隔值,其文件以純文本形式存儲表格數(shù)據(jù)(數(shù)字和文本),本文為大家整理了C語言解析csv文件的方法,需要的可以參考一下2023-06-06

