'Reverse words in a string in C++ [duplicate]
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;
}
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ElfIv |
