0

I'm trying to create a method where an array of char "s" is entered along with 2 other chars 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;

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.