I need to replace the whitespaces " " in a string with @40
and have to do in O(1) space complexity. I cannot create a temp string or use auxiliary memory.
Input: Hello I love coding Coding Ninjas India
Output:Hello@40I@40love@40coding@40Coding@40Ninjas@40India
This is my current code:
#include<iostream>
using namespace std;
string replaceSpaces(string &str)
{
int i=0;
string temp="";
while(i < str.length())
{
if(str[i] ==' ')
{
str.erase(i,1);
str.insert(i,"@40");
}
i++;
}
return str;
}
int main()
{
string s="Hello I love coding Coding Ninjas India";
cout << "Ans--> " << replaceSpaces(s) << endl;
}
When I am not writing str.erase() and directly inserting @40
my code is not running, so I do not understand why we have to use str.erase(i,1) and string by 1 before inserting.