Answer S20
/* Puzzle S20 --- Delete each instance of a particular character from a string */
#include <stdio.h>
#include <stdlib.h>
void deleteCh( char *str, char ch )
{
/* Inspect each character of the string */
while ( *str )
{
/* if the character is to be deleted... */
if ( *str == ch )
{
/* slide all the characters to the right down one */
char *p = str;
while ( *p )
{
*p = *(p+1);
p++ ;
}
/* a new character might need to be deleted */
/* so don't increment str */
}
/* otherwise, move on to the next character */
else
str++ ;
}
}
struct test
{
char str[50];
char ch;
};
int main(int argc, char *argv[])
{
struct test trials[] =
{
{"aXX", 'a'},
{"XXa", 'a'},
{"aXX", 'x'},
{"a", 'a'},
{"aa", 'a'},
{"aaa", 'a'},
{"bca", 'a'},
{"bcaa", 'a'},
{"aaabbbaaa", 'a'},
{"xaxaxa", 'a'},
{"XAAxaa", 'a'},
{"applecart", 'a'},
{"blue berry", 'e'}
};
int j;
for ( j=0; j<sizeof(trials)/sizeof(struct test); j++ )
{
printf( "%s\t", trials[j].str );
deleteCh( trials[j].str, trials[j].ch );
printf( "%c\t%s\n",
trials[j].ch, trials[j].str );
}
return 0;
}