Header Ads

30 - WAP to Squeeze Characters from a String in C

This program Squeeze's Characters from a given String in C.

Program Code :
// WAP to Squeeze Characters from a String 

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

//Squeezing using iteration
char* i_squeeze(char *original, char *del, int *length)
{
 int idx, jdx, kdx = 0;

 //Loop to check the character to be squeezed
 for (idx = 0; del[idx] != '\0'; idx++)
 {
  //Loop to check the char with the original
  for (jdx = 0; original[jdx] != '\0'; jdx++)
  {
   if (original[jdx] != del[idx])
   {
    //Rewriting the original string without the squeeze char
    original[kdx] = original[jdx];
    kdx++;
   }
  }
  //Writing null at last
  original[kdx] = 0;
  //Resetting index
  kdx = 0;
 }
 return original;
}


// Main Program Function
int main()
{
 char *original = malloc(100), *del = malloc(100), ch;
 int length = strlen(original); 

 while (1)
 {
  printf("\n Enter the Original String : ");
  scanf("%[^\n]", original);

  printf(" Enter the Characters to be Squeezed : ");
  scanf("%s", del);
  getchar();
  if (*(i_squeeze(original, del, &length)) != '\0')
  {
   printf(" The String after Squeezing is '%s' \n", original);
  }
  else
  {
   printf(" The String after Squeezing is 'NULL'. \n");
  }
  printf("\n");
  printf(" To Continue press [Y/n] : ");
  ch = getchar();
  //while (getchar() != '\n');
  if (!(ch == 'y' || ch == 'Y'))
  {
   break;
  }
  getchar();
 }
 free(original);
 free(del);
 return 0;
}

Program Output: 

 

No comments