String conversion from uppercase to lowercase and vice-versa..
1. Using built-in tolower / toupper and transform function.
Transform function applies a function on a range of elements that need modification. For example ( changing upper case to lower case and vice-versa )
The template of transform function is as below
Output_Iterator transform ( Input_Iterator first1, Input_Iterator last1, Output_Iterator result, Unary_Operation op );
C++ : String uppercase to lowercase using tolower (toupper) and transform function.
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
int main() {
std :: string str_ = "Snap BACK To RealiTY, WHOOP There GOES GraviTY";
std :: cout << "[ Original string ] : " << str_ << std :: endl;
// Converting to lower case
std :: transform (str_.begin(), str_.end(), str_.begin(), ::tolower);
std :: cout << "[ String lowercase ] : " << str_ << std :: endl;
// Converting to upper case
std :: transform (str_.begin(), str_.end(), str_.begin(), ::toupper);
std :: cout << "[ String uppercase ] : " << str_ << std :: endl;
return 0;
}
Output
[ Original string ] : Snap BACK To RealiTY, WHOOP There GOES GraviTY
[ String lowercase ] : snap back to reality, whoop there goes gravity
[ String uppercase ] : SNAP BACK TO REALITY, WHOOP THERE GOES GRAVITY
2. Modifying the ASCII value.
The ASCII value of capital letters is [ A : 65 … Z : 90 ] and the ASCII value of small letters is : [ a : 97 … z : 122 ].
To convert a string from uppercase to lowercase we just check the ASCII value of each character in the range 65 to 90 and add 32 to it.
i.e we change the uppercase character to lowercase.
C++ : Converting a string from uppercase to lowercase and vice-versa by changing the ASCII value.
#include <algorithm>
#include <cctype>
#include <string>
#include <iostream>
using namespace std;
int main() {
string str_ = "SALE : EVerytHING , Must GO !!";
cout << "[ Original string ] : " << str_ << endl;
// Converting to lower case
for ( auto& ch : str_) {
if ( ch >= 'A' and ch <= 'Z') {
ch = ch + 32;
}
}
cout << "[ String lowercase ] : " << str_ << endl;
str_ = "here and now.";
cout << "\n[ Original string ] : " << str_ << endl;
// Converting to upper case
for ( auto& ch : str_) {
if ( ch >= 'a' and ch <= 'z') {
ch = ch - 32;
}
}
cout << "[ String uppercase ] : " << str_ << endl;
return 0;
}
Output
[ Original string ] : SALE : EVerytHING , Must GO !!
[ String lowercase ] : sale : everything , must go !!
[ Original string ] : here and now.
[ String uppercase ] : HERE AND NOW.