Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the case of a string in C++?

Tags:

c++

string

case

I have a string that may contain numbers as well as upper and lower case letters. I need to convert all the uppercase letters to lowercase and vice versa. How would one go about this?

like image 732
rectangletangle Avatar asked Nov 03 '10 05:11

rectangletangle


2 Answers

Here's a way to do it without boost:

#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;
}
like image 161
David Titarenco Avatar answered Sep 21 '22 13:09

David Titarenco


Iterate the string and use isupper() to determine if each character is uppercase or not. If it's uppercase, convert it to lowercase using tolower(). If it's not uppercase, convert it to uppercase using toupper().

like image 34
Matthew Iselin Avatar answered Sep 21 '22 13:09

Matthew Iselin