2. Data Structure Program | Read Now

Data Structure Lab program -02

  • Design, Develop and Implement a Program in C for the following operations on Strings
    1. Read a main String (STR), a Pattern String (PAT) and a Replace String (REP)
    2. Perform Pattern Matching Operation: Find and Replace all occurrences of PAT in STR with REP if PAT exists in STR. Report suitable messages in case PAT does not exist in STR
  • Support the program with functions for each of the above operations. Don’t use Built-in functions.

Program-2 Code [patternmatching.c]

#include<stdio.h>

void main()
{
  char s[20],pat[20],rep[20],ans[30];
  int i,j,k,l,flag;
  printf("\nEnter string:");
  scanf("%s",s);
  printf("\nEnter pattern:");
  scanf("%s",pat);
  printf("\nEnter replacement:");
  scanf("%s",rep);
  for(i=0,k=0;s[i]!='\0';i++)
  {
    flag=1;
    for(j=0;pat[j]!='\0';j++)
      if(s[i+j]!=pat[j])
        flag=0;
    l=j;
    if(flag)
    {
      for(j=0;rep[j]!='\0';j++,k++)
        ans[k]=rep[j];
      i+=l-1;
    }
    else
      ans[k++]=s[i];
  }
  ans[k]='\0';
  printf("%s",ans);

}

Data Structure -How to Run this Program

  • Step-1: Copy the above code
  • Step-2: Paste it in any C compiler [Codeblocks/Dev C++/ VsCode etc]
  • Step-3: Save the file name with .C extension
  • Step-4: Compile the program
  • Step-5: Run the program
  • Step-6: Program Execution Successful

Leave a Reply

Your email address will not be published. Required fields are marked *

WhatsApp Icon Join For Job Alerts