Monday, December 1, 2014

String replacement program in C

A program to find a particular pattern in a string and replace all occurrences of that pattern with a new pattern to produce a modified string.


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

void main()
{
  char str[100], pattern[50], replace[50], new_str[100], temp[50];
  int l1, l2, l3, flag_eos = 0, pattern_found = 0;
  int i = 0, j, k, n;
  printf("\n###################################\n");
  printf("Enter any string\n");
  gets(str);
  printf("\n###################################\n");
  printf("Enter pattern to be replaced\n");
  gets(pattern);
  printf("\n###################################\n");
  printf("Enter new pattern\n");
  gets(replace);

  l1 = strlen(str);
  l2 = strlen(pattern);
  l3 = strlen(replace);
 
  while(flag_eos == 0)
  {
    for(; i < l1; i++)
      // if any character of str = first character of the pattern
      if((str[i] == pattern[0]) && (i + l2 - 1 < l1))
      {
        for(j = i, k = 0; j < i + l2; j++)
          temp[k++] = str[j];
        temp[k] = '\0';
        break;
      }
    if(i == l1)
    {
      flag_eos = 1;
      temp[0] = '\0';
    }
    if(strcmp(temp, pattern) == 0)
    {
      pattern_found = 1;
      n = 0;
      for(j = 0; j < i; j++)
        new_str[n++] = str[j];
      for(j = 0; j < l3; j++)
        new_str[n++] = replace[j];
      for(j = i + l2; j < l1; j++)
        new_str[n++] = str[j];
      new_str[n] = '\0';
      // Recompute the new string length and
      // continue to look for more occurrences
      strcpy(str, new_str);
      l1 = strlen(str);
    }
    else
      i = i + 1;
  }
  if(pattern_found == 1)
  {
    printf("\n###################################\n");
    printf("The modified string is \n");
    puts(str);
    printf("###################################\n");
  }
  else
  {
    printf("\n###################################\n");
    printf("Pattern not found in the string !!!\n");
    printf("###################################\n");
  }
}

Written by

No comments:

Post a Comment