Search code examples
c++toggletouppertolower

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

Solution

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