简体   繁体   中英

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

Input:

abcdE

Output:

ABCDe

I am looking for an efficient and less code solution for this code:

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

I suppose you should use std::transform :

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

You can also use std::for_each from algorithm library.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM