-
Notifications
You must be signed in to change notification settings - Fork 1
/
txtfind.c
163 lines (135 loc) · 2.95 KB
/
txtfind.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#include <stdio.h>
#include <string.h>
#include "txtfind.h"
#define LINE 256
#define WORD 30
#define TRUE 1
#define FALSE 0
int get_line(char *s)
{
char c = getchar();
int numOfChars = 0;
if (c != '\n')
{
numOfChars++;
s[0] = c;
}
for (int i = 1; c != '\n' && i < LINE && c != '\r' && c != EOF; i++)
{
c = getchar();
s[i] = c;
numOfChars++;
}
return numOfChars - 1;
}
int get_word(char w[])
{
char c = getchar();
if (c == '\n' || c == ' ' || c == '\t' || c == '\r' || c == EOF)
{
return -1;
}
int numOfChars = 0;
for (int i = 0; c != '\n' && c != ' ' && c != '\t' && c != '\r' && i < WORD && c != EOF; i++)
{
w[i] = c;
numOfChars++;
c = getchar();
}
w[numOfChars] = '\0';
return numOfChars;
}
int substring(char *str1, char *str2){
int numOfSimilarLetters = 0;
int len1 = strlen(str1);
int len2 = strlen(str2);
if (len1 < len2) return 0;
for (int i=0; i<len1-len2+1; i++){
for (int j=0; j<len2; j++){
if (*(str1+i+j) == *(str2+j)){
numOfSimilarLetters++;
}
else break; // else move to next i
}
if (numOfSimilarLetters == len2){
return 1;
}
else numOfSimilarLetters = 0;
}
return 0;
}
int similar(char *s, char *t, int n)
{
int len_s = strlen(s);
int len_t = strlen(t);
if (substring(s, t) && substring(t, s) && n == 0)
{
return TRUE;
}
if (len_s < len_t)
{
return FALSE;
}
int similar = 0;
int i = 0, j = 0; // i->t , j->s
while (i < len_t && j < len_s)
{
if (*(t + i) == *(s + j))
{
similar++;
i++;
j++;
}
else
{
j++;
}
}
if (len_s - similar == n)
{
return TRUE;
}
return FALSE;
}
void print_lines(char *str)
{
int line_len = 1;
int lineToPrint = FALSE;
while (line_len != 0 && line_len != '\r')
{
char line[LINE] = {0};
line_len = get_line(line);
lineToPrint = substring(line, str);
if (lineToPrint)
{
for (int i = 0; i < line_len; i++)
{
printf("%c", line[i]);
}
printf("\n");
}
}
}
void print_similar_words(char *str)
{
int word_len = 0;
int wordToPrint = FALSE;
while (word_len != ' ' && word_len != '\t' && word_len != '\r' && word_len != '\n')
{
char word[WORD] = {0};
word_len = get_word(word);
if (word_len == -1)
{
return;
}
wordToPrint = similar(word, str, 1)||similar(word, str ,0);
if (wordToPrint)
{
for (int i = 0; i < word_len; i++)
{
printf("%c", word[i]);
}
printf("\n");
}
}
}