#include <iostream>
#include <string>
using namespace std;
void replace_char(char *str, char to_replace, const char *replacements) {
// create these two to keep track of which character we are on in both strings
int strCounter = 0;
int replacementsCounter = 0;
while(true) {
// if we reach the end of the string then break out of the loop
if(*(str + strCounter) == '\0') break;
// if it finds the current character matches the char to replace
else if(*(str + strCounter) == to_replace) {
// replaces the character in the string
str + strCounter = *(replacements + replacementsCounter);
if(*(replacements + replacementsCounter) == '\0') {
// we are out of replacement characters
break;
}
else {
// we used a replacement character so move onto the next one
replacementsCounter++;
}
}
// move onto the next character in the string
strCounter++;
}
}
int main() {
char str1[6] = "hello";
replace_char(str1, 'h', "jeans");
string str1_string("jello");
assert(str1 == str1_string);
char str2[7] = "giggle";
replace_char(str2, 'g', "ab");
string str2_string("aibgle");
assert(str2 == str2_string);
char str3[5] = "eecs";
replace_char(str3, 'e', "pine");
string str3_string("pics");
assert(str3 == str3_string);
char str4[12] = "x-x-x-x-x-x";
replace_char(str4, 'x', "abcd");
string str4_string("a-b-c-d-x-x");
assert(str4 == str4_string);
char str5[11] = "statistics";
replace_char(str5, 's', "");
string str5_string("statistics");
assert(str5 == str5_string);
}
Repro below. This shouldn't be a syntax error.