user3568692
user3568692

Reputation: 3

Replace character

I've done this code so far but I don't get a final output (blank). Output that I expected is when I put a string Hello World and replace o with i the string will be Helli Wirld. But I got nothing in the final output.

char * substitute(char *, char, char);

int main(void){

  char arr[255];
  char i,j;
  printf("Enter a string: ");
  gets(arr);
  printf("Find a char: ");
  scanf(" %c", &i);
  printf("Replace with: ");
  scanf(" %c", &j);
  printf("Final output: ");
  printf("%s", substitute(arr, i, j));
  return 0;
}

char * substitute(char *data, char find, char replace){
  while(*data!='\0'){
   if(*data==find){
   *data=replace;
   }
  data++;
  }
  return data;
}

Upvotes: 0

Views: 139

Answers (1)

Ingo Leonhardt
Ingo Leonhardt

Reputation: 9894

In substitute() you return the pointer data that you have incremented in your while loop, so now it points to the terminating '\0' and that's what you printf().

You could either use a separate local variable for traversing the string, or you don't use the return value of substitute() at all and replace

printf("%s", substitute(arr, i, j));

by

substitute(arr, i, j);
printf("%s", arr );

Upvotes: 3

Related Questions