Experiment-2.pptx:pattern matching program

ambikavenkatesh2 0 views 10 slides Oct 15, 2025
Slide 1
Slide 1 of 10
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10

About This Presentation

DS Lab program 2


Slide Content

Data Structures Lab [BCSL305] Department of CSE- Data Science

Program 2: Develop a Program in C for the following operations on Strings Read a main String (STR), a Pattern String (PAT) and a Replace String (REP) 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. Department of CSE- Data Science

Procedure Step 1: Input Read STR (main string) Read PAT (pattern to find) Read REP (replacement string) Step 2: Initialization Set i = 0 (index for STR) Set j = 0 (index for ANS, the result string) Set flag = 0 (to track if any match is found) Department of CSE- Data Science

Step 3: Pattern Matching Loop While STR[ i ] is not end of string: Check if PAT matches at position i in STR If match found: Copy REP to ANS Advance i by length of PAT Set flag = 1 If no match: Copy current character from STR to ANS Increment i and j Department of CSE- Data Science

Step 4: Output If flag == 0, print "Pattern not found" Else, print ANS as the modified string Department of CSE- Data Science

Program #include < stdio.h > void read(char STR[], char PAT[], char REP[]); void match( const char STR[], const char PAT[], const char REP[], char ANS[]); int main() { char STR[100], PAT[100], REP[100], ANS[300]; read(STR, PAT, REP); match(STR, PAT, REP, ANS); return 0; } Department of CSE- Data Science

void read(char STR[], char PAT[], char REP[]) { printf ("Enter the main string STR: "); gets(STR); printf ("Enter the pattern string PAT: "); gets(PAT); printf ("Enter the replace string REP: "); gets(REP); } Department of CSE- Data Science

void match( const char STR[], const char PAT[], const char REP[], char ANS[]) { int i = 0, j = 0, k, m, flag = 0; while (STR[ i ] != '\0') { m = i ; k = 0; // Check for pattern match while (STR[m] == PAT[k] && PAT[k] != '\0’) { m++; k++; } Department of CSE- Data Science

// If pattern found if (PAT[k] == '\0') { flag = 1; k = 0; while (REP[k] != '\0') { ANS[ j++ ] = REP[k++]; } i = m; } else { ANS[ j++ ] = STR[ i ++]; } } Department of CSE- Data Science

ANS[j] = '\0'; // Null-terminate result string if (flag == 0) printf ("Pattern not found.\n"); else printf ("Resultant string is: %s\n", ANS); } Department of CSE- Data Science
Tags