CSM217: C for Computer Scientists

Lecture 3: Exercise 1: Solution

// squeeze will delete chars in the original string

#include <stdio.h>

void squeeze(char [], char []); 

main() {
 char s1[] = "Thiis is a string";
 char s2[] = "gicsx ";

 printf("Chars to delete: %s\n", s2);
 printf("Before squeezing: %s\n", s1);
 squeeze(s1, s2);
 printf("After squeezing: %s\n", s1);
}

void squeeze(char s1[], char s2[]) {
 int i, j, k; // array subscripts
 
 for (i=0; s2[i] != '\0'; i++) { // process chars to delete
  for (j=k=0; s1[j] != '\0'; j++) { // process original string
   if (s1[j] != s2[i]) {
    s1[k++] = s1[j]; // pull back the next character
   }
  }
  s1[k] = '\0'; // terminate string with a null character
 }
}