-
Notifications
You must be signed in to change notification settings - Fork 1
/
CountWordInString.c
80 lines (63 loc) · 1.79 KB
/
CountWordInString.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
// count_string.c
// Count the number of times a search string appears in a text.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LENGTH_SEARCH 15
#define LENGTH_LINE 80
int count_substr(char [], char [], char);
int main(void) {
char str[LENGTH_SEARCH + 1], str_backup[LENGTH_SEARCH + 1];
char line[LENGTH_LINE + 1];
char sensitivity;
int len, count;
printf("Enter search string with <= %d characters: ", LENGTH_SEARCH);
fgets(str, LENGTH_SEARCH+1, stdin);
len = strlen(str);
if (str[len - 1] == '\n')
str[len - 1] = '\0';
printf("search string: \"%s\"\n", str);
strcpy(str_backup, str);
printf("Search with case-sensitive ('y' or 'n')? ");
scanf("%c%*c", &sensitivity);
if (sensitivity == 'y')
printf("Case-sensitivity is on.\n");
else
printf("Case-sensitivity is off.\n");
count = 0;
printf("Enter lines of text, each with <= %d characters,\n", LENGTH_LINE);
printf("and end with an empty line.\n");
while (1) {
fgets(line, LENGTH_LINE+1, stdin);
len = strlen(line);
if (line[len - 1] == '\n')
line[len - 1] = '\0';
len = strlen(line);
printf("Line entered: \"%s\"\n", line);
if (len == 0)
break;
count += count_substr(line, str, sensitivity);
}
printf("Number of times \"%s\" appears: %d\n", str_backup, count);
return 0;
}
// Count the number of times str occurs in line,
// depending on case-sensitivity.
int count_substr(char line[], char str[], char sensitivity) {
int i, count = 0;
char *stringP;
do{
if(sensitivity == 'n'){
for(i = 0; line[i] != '\0';i++){
line[i] = tolower(line[i]);
}
}
stringP = strstr(line,str);
if(stringP != NULL){
count++;
line = stringP+1;
}
}
while(stringP);
return count;
}