I'm new to C++ and have no prior logical or experience with other programming languages. I've learned on arrays and string today and saw that the null character kinda seperates words from other so getline can get them correctly.
Basicacly what I want to do is, read a sentence for example : Hello my friend
and reverse the sentence to > friend my hello . This is very very similar to a coding problem on the Google Code Jam. I've managed to do it but it's very restricted...
naaokth gave very good solution. I just want to mention that if you want to create string with the words reordered, there's one in-place algorithm (meaning it does not use external memory):
- inverse the direction of each word "olleH ym dneirf"
- inverse the direction of the entire string "friend my Hello"
Spaces should be treated as separate from the word. I am not sure if you would want to do this with punctuated sentence. You may be able to use only two passes (one for inverting the entire sentence and simultaneously detecting where each word ends, which is the first pass, and inverting the words themselves immediately when you discover such word boundary, which is the second pass), but it is much more difficult this way. The easiest way is to first seek where each word ends, and invert the word when you discover it. Iterate all words in this manner. Then you will find where the string ends as by-product from the previous step. Now you can invert the entire string. You can use STL reverse: http://www.cplusplus.com/reference/algorithm/reverse/