Search code examples
c++for-loopif-statementreplacec-strings

Replacing a pair of characters in a string with another


I want to replace a pair of characters with another pair.

For example if want to replace "ax" with "57" and the string is "vksax", it will give out "vks57".

Tried it this way but get a weird output that is only partially correct:

#include <stdio.h>
#include <stdlib.h>

int main()
{
   
char dummy;
int i;
char string[16];
scanf("%s", string);

for(i=0;string[i];i++){
  if(string[i] == 'a'  && string[i+1] == 'x'){
    string[i] = '5' ;
    string[i+1] = '7';
    i=0;  
  }
printf("%s", string) ;
}
   exit(0);
}

I can't figure out why it gives, for example, with an input of 1234ax the output 1234ax1234ax1234ax1234ax123457123457123457123457123457123457


Solution

  • Within the for loop

    for(i=0;string[i];i++){
      if(string[i] == 'a'  && string[i+1] == 'x'){
        string[i] = '5' ;
        string[i+1] = '7';
        i=0;  
      }
    

    this statement

    i=0;  
    

    does not make a sense. Remove it. And instead of

        string[i+1] = '7';
    

    write

        string[++i] = '7';
    

    And move this call

    printf("%s", string) ;
    

    outside the for loop.

    Pay attention to that the variable dummy is declared but not used.

    char dummy;
    

    Remove this declaration.

    And there is no great sense to use exit( 0 ); instead of return 0;.

    And the call of scanf will be more safer if to write it like

    scanf("%15s", string);