• Split a string into individual letters/characters?
    8 replies, posted
I just started learning C++ a week or so ago and I kinda feel like making a little word mixer program. Basically the user enters a string (no numbers or punctuation for now) and I need to split up the string (anything from a simple sentence to an entire paragraph) into individual letters so that I can take those letters and do with then what I like. Any help is appreciated.
A string is already "split up" in the sense that you can access individual characters using array syntax, e.g. mystring[0] for the first letter, mystring[4] for the fifth, and so on. (Rocket, you can use brackets directly on a std::string; no need to convert it to a C string.)
Thanks guys. I was trying to figure out for a while how to make an unknown number of variables (because the user could enter one letter or a couple paragraphs) then the do..while loop hit me :) [CODE]do{ indChar=userText[userTextPos]; userTextPos++; }while(userTextPos<userText.size());[/CODE]
[QUOTE=DeltaSmash;32634261]Thanks guys. I was trying to figure out for a while how to make an unknown number of variables (because the user could enter one letter or a couple paragraphs) then the do..while loop hit me :) [CODE]do{ indChar=userText[userTextPos]; userTextPos++; }while(userTextPos<userText.size());[/CODE][/QUOTE] Next level coding: [code] for(int userTextPos = 0; userTextPos < userText.size(); userTextPos++) { indChar=userText[userTextPos]; } [/code] Does the same thing. For situations like this where it's a simple loop, usually using a for block is the way to go :smile:
Yes I guess that does make it cleaner. Could even remove the curly braces and make it a one-liner.
Don't remove the curly braces, you'll spend more time adding/removing them then actually coding.
IMO that's a bit of an exaggeration, but I still agree. There are occasionally times where I absolutely know I won't need the curly brackets or that adding curly brackets will make it look messy, but for the most part I keep them in, looks cleaner.
[QUOTE=robmaister12;32634999]IMO that's a bit of an exaggeration, but I still agree. There are occasionally times where I absolutely know I won't need the curly brackets or that adding curly brackets will make it look messy, but for the most part I keep them in, looks cleaner.[/QUOTE] Yeah, I was going to write that there's exceptions like guards at the start of a function to check if something isn't NULL and then immediately return, but I didn't really want to do the whole 'except if you absolutely know you won't', because from experience I've never known.
Sorry, you need to Log In to post a reply to this thread.