Saturday, December 4, 2021
HomeTop Coding QuestionWrite a program to reverse word in given string.

Write a program to reverse word in given string.

Given a string of sentence we have to reverse each word of sentence and print the resultant string.

Example:

input: i love geeksprep.
output geeksprep love i

Logic:

step 1- store each word in vector of string.
step 2-iterate the vector in reverse order.

#include<bits/stdc++.h>
using namespace std;
int main()
{
string s="i loves geeksprep";
vector<string>v;
 string k=" ";
for(int i=0;i<s.length();i++)
{
   
    if(s[i]!=' ')//if s[i] is not space then add s[i] value to k
    {
        k+=s[i];
    }
    else
    {
    v.push_back(k);//if space come then  push string into vector
    k="";//initialise k again
    }
}
v.push_back(k);///push the last element
for(int i=v.size()-1;i>=0;i--)
{
    cout<<v[i]<<" ";
}

    
}
geeksprep love i

Time Complexity:O(N)

Space Complexity:O(N)

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments