C++对string进行大小写转换操作方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++对string进行大小写转换操作方法

YAIMZA   2023-03-20 我要评论

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们