【C++】字符串的大小写转换

#include<string>
#include<algorithm>
#include<iostream>

using namespace std;

int main(){
    string s = "abcABC";
    transform(s.begin(), s.end(), s.begin(), ::tolower);

    cout << s << endl; //"abcabc"
    
    string upper;
    upper.resize(s.size());
    transform(s.begin(), s.end(), upper.begin(), ::toupper);
    cout << s << endl; //"abcabc"
    cout << upper << endl; //"ABCABC"

    return 0;
}

transform函数在anlgorithm里,四个参数分别为,①被转换字符串头、②被转换字符串尾、③用来存放转换后的字符串头、④转换类型

在转换大写的例子中,如果没有resize会报错,因为需要事先确定用来存放转换后字符串的大小足够装得下。

参考:http://www.ijophy.com/2014/11/cpp-string-tolower-toupper.html

原文地址:https://www.cnblogs.com/Chilly2015/p/5638242.html