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;
}
Subscribe to:
Posts (Atom)
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...
-
Role Play was conducted for the Topic: Comparison between Bubble sort and Insertion sort on Oct 7, 2021. Topic discussed: Brief description ...
-
Vision To be a centre of excellence recognized nationally and internationally, in distinctive areas of engineering education and research, b...
-
Open Elective: Python Application and Programming Python is dynamically-typed and garbage-collected. It supports multiple programming parad...
No comments:
Post a Comment