Jun 21, 2021

K & R : Exercise 2.4 - squeeze string

K & R : Exercise 2.4 - squeeze string


Write an alternate version of squeeze(s1, s2) that deletes each charecter in s1 that matches any charecter in the string s2.


Hence s1 would be modified removing all the charecters from s1 which are there in s2. First we will traverse s1 charecter by charecter (outer for loop with index i). Second loop (with index j) will traverse s2. Each charecter in s1 is tested against charecter in s2, if found then break is hit so that it is skipped. Solution would looks something like below.

#include <stdio.h>
#include <string.h>

void squeeze(char *s1, const char *s2);
int main()
  char s1[10] = "hello";
  char *s2 = "world";

  printf("Before Squeeze s1 is %s\n", s1);

  squeeze(s1, s2);

  printf("After Squeeze s1 is %s\n", s1);

  return 0;
void squeeze(char *s1,const char *s2)
  int i, j;
  int k = 0;
  for(i = 0; i < strlen(s1); i++) {
    for(j = 0; j < strlen(s2); j++) {
       if(s1[i] == s2[j])
    if(j == strlen(s2)) {
       s1[k++] = s1[i];
  s1[k] = '\0';
  return 0;
Before Squeeze s1 is hello
After Squeeze s1 is he

No comments :

Post a Comment