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