在 C++ 中没有循环从上到下,反之亦然?

upper to lower and vice-versa without loop in C++?

输入:

abcdE

输出:

ABCDe

我正在为这段代码寻找一种高效且代码更少的解决方案:

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

int main() {
    int len, ;
    string data;

    cin >> data;

    len = data.length();

    for (i = 0; i < len; i++)
        if (isupper(data[i]))
            data[i] = tolower(data[i]);
        else
            data[i] = toupper(data[i]);

    cout << data << endl;

    return 0;
}

我想你应该使用 std::transform:

std::string str("abcdE");
std::transform(str.begin(), str.end(), str.begin(), [](char c) {
        return isupper(c) ? tolower(c) : toupper(c);
});

您还可以使用 algorithm 库中的 std::for_each

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

int main() {
    std::string data = "AbcDEf";
    std::for_each(data.begin(), data.end(), [](char& x){std::islower(x) ? x = std::toupper(x) : x = std::tolower(x);});
    std::cout << data<< std::endl;
}