STRING OPERATIONS USING NAIVE IMPLEMENTATION.

Exported from Notepad++
2. Design, Develop and Implement a Program in C for the following operations on Strings a. Read a main String (STR), a Pattern String (PAT) and a Replace String (REP) b. 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. #include <stdio.h> int flag; int string_length( char *s ) { char *p = s; while (*p != '\0') p++; return p - s; } void string_copy( char *s, char *t ) { while ( *s++ = *t++ ); } void string_n_copy( char *s, char *t, int n ) { int i; for ( i = 1; i <= n; ++ i ) *s++ = *t++; *s = '\0'; } void string_cat( char *s, char *t ) { s += string_length(s); string_copy ( s, t); } int brute_force_string_match ( char t[], char p[] ) { int i, j; int n = string_length ( t ); int m = string_length ( p ); for ( i = 0; i <= ( n - m ); ++ i ) { j = 0; while ( ( j < m ) && ( p[j] == t[i + j] ) ) { j = j + 1; } if ( j == m ) return i; } return -1; } int main() { char text[50], pat[50], rep[50]; char buf[50]; int i; printf("\n\nEnter text:\n"); gets(text); printf("\n\nEnter Pattern:\n"); gets(pat); printf("\n\nEnter Replacement String:\n"); gets(rep); while ( 1 ) { i = brute_force_string_match ( text, pat ); if ( i == -1 ) break; string_n_copy ( buf, text, i ); string_cat ( buf, rep ); string_cat ( buf, text + i + string_length ( pat ) ); string_copy ( text, buf ); printf ( "\n\nAfter String Replacement:" ); printf ( "\n\n%s\n\n", text ); flag = 1; } if ( flag == 0 ) printf ( "\nPattern does not exist\n" ); return 0; }

No comments:

Post a Comment

Online Certifications

Python for Beginners Offered by: Christian Drumm, Stephan Jacobs Course dates: 2022-04-05 to 2022-06-01 Topics Python Fundamentals Lists and...