This function recursively replaces every instance of the char "-" in the string "-h-e-l-l-o-", with the char " ". After running the code it gave me a segmentation error, which I'm not sure how to fix. I've included the function call along with the function. Can anyone help?
edit: I fixed the segmentation error, and the code runs, but I've run into another issue. The function doesn't replace '-' with ' '. The compiler just spits out 'h-e-l-l-o' with no modifications.
/**** Recursive string replace > Replaces all instances of a character in a string with another character*****/
void recReplace(string s2, int i, char old, char neW)
{
if(s2[i] == old) //search for old char
{
i = neW; //replace it
i++; //iterate i
recReplace(s2, i, old, neW); //call function
}
elseif(s2[i] == '\0')
return;
}
/* Replaces a character in a string with a new one */
cout << "REPLACE" << endl;
cout << "----------" << endl;
string s2 = "-h-e-l-l-o-";
char oldChar = '-';
char newChar = ' ';
cout << "String: " << s2 << endl;
cout << "> Replace '" << oldChar << "' with '" << newChar << endl;
recReplace(s2, 0, oldChar, newChar);
cout << "String: " << s2 << endl;
cout << endl;
Pass s2 and i by reference, not by value, or neither will return changed values to the calling program. Set s2[i], not i, to neW.
Do you really want to do this by recursion? Also, checking for null termination is not such a natural thing to do with a std::string as with a c-string.
And neW is not a good name for a variable - it's asking for trouble as there is a rather important keyword "new".
std::string replace( std::string str, char old, char replace_with, std::size_t from_pos = 0 )
{
if( from_pos < str.size() ) // if we have not reached the end of the string
{
// replace the char at position from_pos if it is equal to old
if( str[from_pos] == old ) str[from_pos] = replace_with ;
// recursively replace chars at later positions and return the result
return replace( str, old, replace_with, from_pos+1 ) ;
}
elsereturn str ; // reached the end of the string; return it unchanged
}