如何在C++中更改字符串的大小写?

rec*_*gle 3 c++ string case

我有一个字符串,可能包含数字以及大写和小写字母.我需要将所有大写字母转换为小写,反之亦然.怎么会这样呢?

Dav*_*nco 11

这是一种没有提升的方法:

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

char change_case (char c) {
    if (std::isupper(c)) 
        return std::tolower(c); 
    else
        return std::toupper(c); 
}

int main() {
    std::string str;
    str = "hEllo world";
    std::transform(str.begin(), str.end(), str.begin(), change_case);
    std::cout << str;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*lin 8

迭代字符串并用于isupper()确定每个字符是否为大写.如果它是大写的,请使用将其转换为小写tolower().如果它不是大写,请使用将其转换为大写toupper().