-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path3_frequent_words.cpp
More file actions
135 lines (121 loc) · 2.52 KB
/
3_frequent_words.cpp
File metadata and controls
135 lines (121 loc) · 2.52 KB
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
/*
Name: 任务3 找出现次数最多的单词
Copyright:
Author: lizhimin
Date: 20/05/17 17:14
Description: frequent words
*/
#include <stdio.h>
#include <string.h>
const int MAX=100050; //total string length;
const int LEN=200; //single string max length;
char str[MAX]; //all words;
char s[MAX/LEN][LEN]; //string table;
char strnow[LEN];
char strmax[LEN]; //record the max frequence words;
int i,j;
int n=0,line=0,k=0;
int max=0,now=0; //count the (words number) && (max);
int is_del(char ch)
{
// if (!letter) return 1;
if ('A'<=ch && ch<='Z') return 0;
if ('a'<=ch && ch<='z') return 0;
return 1;
}
void str_sort(char s[][LEN],int line)
{
//Two-dimensional array String sorting;
char tmp[LEN]={0};
int i,j;
for (i=0; i<line; ++i)
{
for (j=0; j<line; ++j)
{
if (strcmp(s[j],s[j+1])<0)
{
strcpy(tmp,s[j]);
strcpy(s[j],s[j+1]);
strcpy(s[j+1],tmp);
}
}
}
}
int main()
{
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
//stdin-----------------------
while (scanf("%c",&str[n++])!=EOF)
{
if (is_del(str[n-1]))
str[n-1]=' ';
}
str[n]=' '; //add end space to string;
//initialization array--------
memset(s,'\0',sizeof(s));
//separate string-------------
for (i=0; i<n; i++)
{
if (str[i]==' ')
{
line++; k=0; //add new line;
//printf("%6d\n",line);
}
else
{
s[line][k++]=str[i]; //add new char;
//printf("%c",str[i]);
}
}
//cheak string table----------
for (i=0;i<line;i++)
{
//printf("%s %6d\n",s[i],i);
}
//string sorting--------------
str_sort(s,line);
//printf("init line:%d\n",line);
for (i=0;i<line;i++)
{
if (strcmp(s[i],"")==0) //delete space;
{
line=i;
break;
}
}
//printf("final line:%d\n",line);
//cheak sorting----------------
/*
for (i=0;i<line;i++)
{
printf("%d ",i);
printf("%s\n",s[i]);
}
*/
//count max words length-------
strcpy(strnow,s[0]);
for (i=0;i<line;i++)
{
//printf("%s",s[i]);
if (strcmp(strnow,s[i])==0)
{
now++;
//printf("%s %d\n",s[i],now);
if (now>max)
{
max=now;
//printf("%d %d",max,now);
strcpy(strmax,s[i]); //updated the most frequently words;
}
}
else
{
now=0;
strcpy(strnow,s[i]); //updated the new words;
}
}
printf("The most frequently occurring word %d times \"%s\"\n",max,strmax);
fclose(stdin); fclose(stdout);
return 0;
}