ch2-squeeze string (Remove char from string)

Chapter_2     Exercise_2-3     Automatic_Conversions strcat     Exercise_2-4







squeeze.c     K&R, p. 47         download


#include <stdio.h> // for printf(), scanf(), getchar()

#define LENGTH 100 // max word length

void squeeze(char[], int); // remove all occurrences of a char from a string

int main()
{
char word[LENGTH];
char c;

printf("Type a word: ");
scanf("%s", word); // type the word,
getchar(); // then press Enter
printf("Type a char to remove from \"%s\": ", word);
scanf("%c", &c); // without getchar(), c would be '\n' (Enter)

printf("squeeze(%s, %c): ", word, c);
squeeze(word,c);
printf("%s\n", word);

return 0;
}

void squeeze(char s[], int c) // remove all c from s[]
{
int i, j;

for (i = j = 0; s[i] != '\0'; i++)
{
if (s[i] != c) {s[j++] = s[i];}
}
s[j] = '\0';
}
/*
gcc squeeze.c -o squeeze
./squeeze
Type a word: abracadabra
Type a char to remove from "abracadabra": a
squeeze(abracadabra, a): brcdbr

./squeeze
Type a word: abracadabra
Type a char to remove from "abracadabra": b
squeeze(abracadabra, b): aracadara

./squeeze
Type a word: abracadabra
Type a char to remove from "abracadabra": v
squeeze(abracadabra, v): abracadabra
*/









Chapter_2     Exercise_2-3     AutoConv BACK_TO_TOP strcat     Exercise_2-4



Comments

Popular posts from this blog

Contents

Blogger Page Margins in Contempo