-
Notifications
You must be signed in to change notification settings - Fork 0
/
02.PatternSubstitution.c
85 lines (78 loc) · 1.6 KB
/
02.PatternSubstitution.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*
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>
#include <stdlib.h>
int stringLen(char str[]);
void stringCat(char dest[], char src[]);
void main()
{
int i = 0, j, k = 0, flag = 0;
char STR[50], PAT[15], REP[15], RESULT[50];
printf("Enter String\n");
gets(STR);
printf("Enter Pattern\n");
gets(PAT);
printf("Enter Substitution Key\n");
gets(REP);
while (STR[i] != '\0')
{
j = 0;
while ((STR[i + j] == PAT[j]) && (PAT[j] != '\0'))
{
j++;
}
if (PAT[j] == '\0')
{
flag = 1;
RESULT[k] = '\0';
stringCat(RESULT, REP);
k = k + stringLen(REP);
// Here j will always be equal to string length of pattern.
i = i + (j - 1);
}
else
{
RESULT[k++] = STR[i];
}
i++;
}
RESULT[k] = '\0';
printf("The result is\n");
if (flag)
puts(RESULT);
else
printf("Pattern not found\n");
}
int stringLen(char str[])
{
int len = 0;
while (str[len] != '\0')
{
len++;
}
return len;
}
void stringCat(char dest[], char src[])
{
int i = 0, j = 0;
while (dest[i] != '\0')
{
i++;
}
// i can be computed using strLength function also. Above while block can be replaced as " i = stringLen(dest); ".
while (src[j] != '\0')
{
dest[i + j] = src[j];
j++;
}
return;
}