2

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'm reversing the order of words in a string by storing the last word and then adding space and then storing the second last and so on. But when I print the output it adds a space before printing.

#include<iostream>
#include<string>
#include<vector>
#include<sstream>
using namespace std;
string reverse(string s){
    vector<string> temp;
    string words;
    stringstream ss(s);
    while (ss>>words)
    {
        temp.push_back(words);
    }
    string ans;
    for (int i = words.size()-1; i >=0; --i)
    {
        if (i!=words.size()-1)
        {
            ans+= " ";
        }
        ans+=temp[i];
    }
    return ans;
}
int main(){
    string s("My name is Saad Arshad ");
    cout<<reverse(s);
    return 0;
}

OUTPUT:

" Arshad Saad is name My"

I think the size of words is greater than that of temp thats why its happening but I still need more clarification.

Hudson
  • 312
  • 2
  • 18
  • 4
    [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Jason Nov 18 '22 at 17:18
  • You are almost there. The linked comment from Jason would be a good start. You can also try printing just the first word and reading the code. You got this! – ListsOfArrays Nov 18 '22 at 17:21
  • Side note: `for (int i = words.size()-1; i >=0; --i)` is a great place to use a reverse iterator. `for (auto it = word.rbegin(); it != rend(); ++it)` – user4581301 Nov 18 '22 at 17:39
  • You have tagged `dsa` (Digital Signature Algorithm). I didn't see anything in your post about digital signatures. Did I miss something? – Thomas Matthews Nov 18 '22 at 18:13
  • Note, the algorithm you described should change "I love New York!" to "***York!*** New love I". Note where the exclamation mark is. – Ranoiaetep Nov 18 '22 at 18:27
  • @ThomasMatthews its Data Structures and Algorithms – All-Rounder CREW Nov 19 '22 at 12:34
  • @Ranoiaetep yeah it should be but in my case I want to print it as !York. Any suggestion for printing it as YorK!?? – All-Rounder CREW Nov 19 '22 at 12:37

0 Answers0