tolower question | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

tolower question

Is it possible to make an entire string lowercase without having to loop through each char? https://code.sololearn.com/cJiG9JYPLwZI/?ref=app Somebody made something like this in a discord server I'm in. It simply generates the random capitalization used in a certain spongebob meme. I decided to remake it out of boredom. I decided to make the entire string lowercase to completely randomize the capitalization. Is there a way to make the entire string lowercase without having to loop through the characters?

12th Feb 2019, 11:00 PM
Daniel Cooper
Daniel Cooper - avatar
4 Answers
+ 4
All other languages which have a tolower() essentially does the same thing anyway. Ensuring that each character is lowercase/uppercase is an O(n) task, so iteration is mandatory (either you do it or the built-in function does). The SO link provided contains the example using std::transform, which is the best you can get if you don't want to write loops. I'm wondering if regex can be used to achieve the task.
13th Feb 2019, 6:08 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
An old-school yet efficient way to do so is catching the uppercase characters while getting them from the input stream as follow #include <iostream> #include <string> #include <cctype> using namespace std; int main() { string s = ""; char c; while ( cin.get(c) ) { if ( c == '\n' ) break; s += tolower(c); } cout << s; } this way, the program gets one line of string, converts it to proper lowercase equivalent, and then appends it to initialized string. O(0)! ;) Live version: https://rextester.com/KAVJ12865
13th Feb 2019, 8:35 AM
Babak
Babak - avatar
+ 3
Welp Guess I gotta Iterate. Thanks Arushi Singhania
12th Feb 2019, 11:25 PM
Daniel Cooper
Daniel Cooper - avatar