Write your question here.
Hello everyone i was tasked to write a program that takes a word/sentence then reverses the order of the word/sentence. I.E.:
I like c++
++c like I
I cannot use #algorithms.What I did didn't work. I can't think of a solution but here is my starting code.
string reverseWords(string str)
{
int posStart=0,posEnd=0;
vector<string> Data;
do
{
for(posEnd=posStart;posEnd<str.size();++posEnd)
if(str[posEnd]==' ')
break;
posEnd-=posStart;//We want difference between (start position and end position) for use below:
if(posEnd>0)
Data.push_back(str.substr(posStart,posEnd));//start position and number of characters
else
Data.push_back(str.substr(posStart));
posStart+=posEnd+1;
}while(posStart<str.size());
str="";
for(int i=0;i<Data.size();++i)
str += Data[Data.size()-1-i]+' ';
return str;
}
Enter a string: This is a string
Reversed string: gnirts a si sihT
Reversed words: string a is This
Press <enter> to exit console:
Finding the spaces and take a substring of the current string:
http://www.cplusplus.com/reference/string/string/substr/
Afterwards, accumulate the words in reverse order, into a single string and return the string.
A simpler way? possibly, but it would depend on your design; string parsing was applied both times, in the previous post and the above.