I have written the code and according to me code should be working but it is not working. It is giving me runtime error. can anybody check my ques my help me with the same?
Here is my code
#include <bits/stdc .h>
using namespace std;
string replaceSpaces(string str){
int spaces_count = 0;
int length = str.length();
for(int i = 0 ; i < str.length() ; i ){
if(str[i] == ' ' ){
spaces_count ;
}
}
int new_length = length spaces_count * 2 1;
int index = new_length - 1;
str[index] = '\0';
index--;
for(int j = length - 1 ; j >=0 ; j--){
if(str[j] == ' '){
str[index] = '0';
str[index-1] = '4';
str[index-2] = '@';
index = index - 3;
}
else{
str[index] = str[j];
index--;
}
}
return str;
}
int main() {
cout << replaceSpaces("My name is Khan");
}
CodePudding user response:
std::string creates a buffer for the size of the string, when you re-size it, you are using more space, and that is overflowing the allocated buffer.
Typically the best pattern for this sort of code, is not to do an in-space modification, but to create a new string which takes the output.
CodePudding user response:
std::string
already has a replace
member function, so you can do something like this:
std::string replaceSpaces(std::string input) {
for (std::size_t i = 0; i < input.length(); i ) {
if (input[i] == ' ')
input.replace(i, 1, "@40");
}
return input;
}
Although it doesn't arise with this example, there is one situation that can require some care to handle correctly: if the replacement string also contains the string you're trying to replace (e.g, replacing each space with two consecutive spaces) you need to be careful about starting your next iteration of searching just after the end of the replacement value you just inserted -- otherwise, you can end up doing infinite replacements (or at least until you run out of available space).
CodePudding user response:
you can do following:
#include <bits/stdc .h>
using namespace std;
string replaceSpaces(string str){
int n = str.size();
string tmp;
for(int i=0; i<n; i ) {
if(str[i] == ' ') {
tmp.push_back('@');
tmp.push_back('4');
tmp.push_back('0');
}
else {
tmp.push_back(str[i]);
}
}
return tmp;
}
int main() {
cout << replaceSpaces("My name is Khan");
}