I have just started learning C++. I am writing a program to reverse the order of words in a string. If there is a sentence,"I love New York!". It should be changed to, "!York New love I".
I am using the algorithm which has two simple steps.
- Reverse the string.
- Reverse the letters of words.
For example, for above string, i will first convert it to, "!kroY weN evol I" and then i will change letters of words like "!kroY" to "York!".
Now the problem is that how would i know that from where the word starts and where it ends. This is what i have done so far. But this program is not working as intended. I am unable to identify the word and then reverse it.
#include <iostream>
#include <string>
std::string reverseText(std::string x){
std::string y;
for(int i=x.size()-1;i>=0;i--) y += x[i];
return y;
}
std::string reverseWords(std::string x){
std::string y = reverseText(x);
bool wordFound = true;
std::string temp1,ans;
for(size_t i=0;i<y.size();i++){
if(wordFound){
if(y[i]!=' ') temp1+=y[i]; // if there is a letter, store that in temp1.
else if(y[i]==' ') // if there is a space, that means word has ended.
{
ans += reverseText(temp1); // store that word, in ans.
temp1=" ";
wordFound=false;}
}
if(y[i]==' ' && y[i+1]!=' ') wordFound=true;
}
return ans;
}
int main(){
std::cout<<reverseWords("My name is Michael");
}
Output : Michaelis name