日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++對string進行大小寫轉換操作方法_C 語言

作者:YAIMZA ? 更新時間: 2023-04-08 編程語言

C++對string進行大小寫轉換操作方法

方法一:

使用C語言之前的方法,使用函數,進行轉換

#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來實現該功能

#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大小寫轉換

1、通過單個字符轉換,使用C的toupper、tolower函數實現

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

int main(){
    string str = "ancdANDG";
    cout << "轉換前的字符串: " << str << endl;
    
    for(auto &i : str){
        i = toupper(i);//i = tolower(i);
    }    
    cout << "轉換后的字符串: " << str << endl;
    
    //或者
    for(int i = 0;i < str.size();++i){
		str[i] = toupper(s[i]);//str[i] = toupper(s[i]);
	}
	cout << "轉換后的字符串: " << str << endl;
	
	return 0;
}

2、通過STL的transform實現

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main(){
    string str = "helloWORLD";
    cout << "轉換前:" << str << endl;
    
    //全部轉換為大寫
    transform(str.begin(), str.end(), str.begin(), ::toupper);    
    cout << "轉換為大寫:" << str << endl;    
    
    //全部轉換為小寫
    transform(str.begin(), str.end(), str.begin(), ::tolower);    
    cout << "轉換為小寫:" << str << endl; 
    
    //前五個字符轉換為大寫
    transform(str.begin(), str.begin()+5, str.begin(), ::toupper);
    cout << "前五個字符轉換為大寫:" << str << endl; 
    
    //后五個字符轉換為大寫
    transform(str.begin()+5, str.end(), str.begin()+5, ::toupper);
    cout << "前五個字符轉換為大寫:" << str << endl; 
    
    return 0;
}

原文鏈接:https://blog.csdn.net/qq_37941471/article/details/81988702

欄目分類
最近更新