0

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; 
} 




  • You are passing the strings by value. Each time you call a function you are creating a copy of the string that is manipulated in the function. – Martin York May 07 '22 at 06:22

1 Answers1

0

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)

ElfIv
  • 21
  • 2