简体   繁体   中英

c++ A string with uppercase and lowercase

I want to ask how can I make a string in c++ that will have uppercase and lowercase? For instance, when the user will put the word forest, I want after the word forest to be like that forEST or FOreST and FORest.

It is possible to randomly uppercase and lowercase the characters of a string the following way:

#include <random>
#include <cctype>
#include <algorithm>

std::string random_uppercase_lowercase(std::string s) {
    std::random_device rd;
    std::default_random_engine generator(rd());
    std::uniform_int_distribution<> distribution(0,1);

    std::transform(s.begin(), s.end(), s.begin(),
        [&](int ch) {
            if (distribution(generator)) {
              return std::toupper(ch);
            } else {
              return std::tolower(ch);
            }
    });
    return s;
}

Try converting the std::string into char and see for each letter. If it's an uppercase, then convert into lowercase and vice versa.

A simple code explanation is here:

#include <iostream>

int main(void) {
    std::string string;

    std::cout << "Enter a string: ";
    std::getline(std::cin, string);

    size_t len = string.length();
    char *pString = new char[len + 1]; // + 1 for null terminator

    strcpy(pString, string.c_str()); // copies 'string' into 'pString'

    for (int i = 0; i < len; i++) {
        if (isupper(pString[i]))
            pString[i] = tolower(pString[i]); // tolower() when isupper()
        else
            pString[i] = toupper(pString[i]); // toupper() when islower()
    }

    std::cout << pString << std::endl; // prints the converted string

    return 0;
}

A sample output is as follows:

Enter a string: HeLLO wOrlD
hEllo WoRLd

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