Puzzle S18

Replace every instance of one character with another

[E-4] Write a function that replaces every instance of a particular character in a string with another character. The prototype of the function is:

void replace( char *str, char old, char new ); 

Replace every character old in str with character new. For example, replace( "applecart", 'a', 'u') changes "applecart" into "upplecurt".

Here is a testing function:

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

void replace( char *str, char old, char new )
{
}

struct test
{
  char str[50];
  char old;
  char new;
};

int main(int argc, char *argv[])
{
  struct test trials[] =
  {
    {"aaa", 'a', 'b'},
    {"aaa", 'x', 'b'},
    {"abc", 'a', 'b'},
    {"bca", 'a', 'b'},
    {"bca", 'a', 'a'},
    {"aaabbbaaa", 'a', 'b'},
    {"xaxaxa", 'a', 'b'},
    {"XAAxaa", 'a', '*'},
    {"applecart", 'a', 'u'},
    {"blue berry", 'e', 'o'}
 };

  int j;
  for ( j=0; j < sizeof(trials)/sizeof(struct test); j++ )
  {
    printf( "%s\t", trials[j].str );
    replace( trials[j].str, trials[j].old, trials[j].new );
    printf( "%c\t%c\t%s\n",
        trials[j].old, trials[j].new, trials[j].str );
  }

 
  return 0;
}


Answer         Next Page         Previous Page Home