Reverse string without reversing words

Reverse string without reversing words

Given a string we have to print the reverse of the string without reversing the word. Let’s see an example.

Input: welcome to tutorialheap please visit regular to learn
Output: learn to regular visit please tutorialheap to welcome

Also read: Program to reverse a string, Program to reverse words in a string

There are many solutions to this problem. Here we discuss one of them. If you want to share any other method please comment below.



Steps to follow

1. Reverse the words of string
2. Reverse the string

For example we have a string as give below:

welcome to tutorialheap please visit regular to learn

According to first step we will reverse the words of the string. The result will be:

emoclew ot paehlairotut esaelp tisiv raluger ot nrael

After this we will reverse the resultant string and the output will be:

learn to regular visit please tutorialheap to welcome

So now let’s see the program for reversing the string without reversing the words.

Program

Reverse string without reversing words

#include<iostream>
#include<algorithm>
#include<string>

using namespace std;

void reverseString(string &str){
    
    //Two variables to keep track of words
    int start=0,end=0;
    
    for(int i=0;i<str.length();i++){
        
        if(str[i] == ' '){
           //if space, means a end of a word, then reverse the word
           reverse(str.begin()+start,str.begin()+end+1);
           
           //assign the variables the next position of new word
           start=end = i+1;
        }
        else{
            //else this is not the end of the word
            end = i;
        }
        
    }
    
    //reverse the last word
    reverse(str.begin()+start,str.begin()+end+1);
    
    //reverse the whole string
    reverse(str.begin(),str.end());
}

int main(){

string str = "Welcome to TutorialHeap please visit regular to learn";

reverseString(str);

cout<<str;
    
    return 0;
}

Output

learn to regular visit please TutorialHeap to Welcome

Leave a Reply

Your email address will not be published. Required fields are marked *