Reverse words in a string in C++

Can anyone please tell that why the below written code isnt working , theres no error but its simply printing the string which was passed and is not reversing it.

Logic: First reverse individual words and after reversing all the words in a string simply reverse the entire string.

I/P : hello world O/P : world hello

Below is the code:


#include <bits/stdc++.h> 
using namespace std; 

void reverse(string str,int low, int high){
    while(low<=high){
        swap(str[low],str[high]);
        low++;
        high--;
    }
}

void reverseWords(string str){
    int start=0;
    int n = str.length();
    for(int end=0;end<n;end++){
        if(str[end]==' '){
            reverse(str,start,end-1);
            start=end+1;
        }
    }
    reverse(str,start,n-1);
    reverse(str,0,n-1);
    
    cout<<str;
}
 
int main() 
{ 
    string s = "Welcome to Gfg";
    
    cout<<"After reversing words in the string:"<<endl;
    reverseWords(s);
    
    
    return 0; 
} 




1 answer

  • answered 2022-05-07 05:35 ElfIv

    You will have to use references to change the string. When you input the string as a parameter into the "reverse" funtion, what is does is create another string to accept the original string (which is copying the string over), so when you use "swap" in the function, you changed the copied version of the string but not the original string. What you can do is to change the parameter type from "string" (string) to "string&" (string reference)

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum