Reputation: 1
I'm trying to create a method where an array of char
"s" is entered along with 2 other char
s char1
and char2
, this method called substitute
will then search through the array and if it spots an instance of char1
FOLLOWED by "!", it will replace that char1
with char2
.
However, when testing my method it doesn't seem to do that, the if
statement is never satisfied.
Please help.
substitute method
void substitute(char* s, char c1, char c2)
{
int n = strlen(s);
for (int i = 0; i <= n; i++)
{
if(s[i] == c1 && s[i+1] == '!')
{
s[i] = c2;
}
i++;
}
}
test input
char s[] = "la!bellabella!bel";
char c1 = 'a';
char c2 = 'x';
substitute(s,c1,c2);
cout << s << endl;
Upvotes: 0
Views: 53
Reputation: 52471
Your code increments i
twice - once as part of for
statement, and again in the body of the loop. The effect is that you only check even-numbered characters, skipping every other character.
Upvotes: 1