文学研究人员需要统计某篇英文文章中某些单词出现的次数和位置,编写一个实现这一目标的文字统计程序。假设需要统计的单词集合称为特定单词集。英文文章是由回车符(‘\n’)隔开的一行一行的文本字符串组成,位置用单词所在行的行号来表示。则程序的功能是统计特定单词集中每个单词在指定文件中出现的次数和出现的行号。
文本串非空且以文件形式存放,统计匹配的词集非空。文件名和词集均由用户从键盘输入;
- “单词”定义:由字母构成的字符序列,中间不含空格字符且区分大小写;
- 待统计的“单词”在文本串中不跨行出现,它或者从行首开始,或者前置若干空格字符;
- 在计算机终端输出的结果是:单词,出现的次数,出现的位置所在行的行号,同一行出现两次的只输出一个行号;
- #include <stdio.h>
- #include <string.h>
- #define MAX_WORD 30
- #define MAX_LOCATION 1000
- #define MAX_ROW_LEN 9999
- #define MAX_TarStr 100
- typedef struct rc {
- int row;
- int column;
- }Rc;
- typedef struct tarStr {
- char word[MAX_WORD];
- Rc position[MAX_LOCATION];
- int pospos;
- int count;
- }TarStr;
- TarStr tar[MAX_TarStr];
- char Tempfgets[MAX_ROW_LEN];
- void FindStr(char* a, TarStr* tar, int ctar, int row) {
- char temp[MAX_ROW_LEN] = { 0 };
- int n, i, j;
- int word = 0;
- n = strlen(a);
- for (i = 0; i < n; i++)
- {
- if (a[i] == ' ' || a[i] == ',' || a[i] == '.')
- {
- if (word != 0) {
- temp[word] = '\0';
- for (j = 0; j < ctar; j++)
- if (strcmp(tar[j].word, temp) == 0) {
- tar[j].count++;
- tar[j].position[++tar[j].pospos].row = row;
- tar[j].position[tar[j].pospos].column = i - word;
- }
- word = 0;
- }
- }
- else
- temp[word++] = a[i];
- }
- if (word != 0) {
- temp[word] = '\0';
- for (j = 0; j < ctar; j++)
- if (strcmp(tar[j].word, temp) == 0) {
- tar[j].count++;
- tar[j].position[++tar[j].pospos].row = row;
- tar[j].position[tar[j].pospos].column = i - word;
- }
- word = 0;
- }
- }
- int main()
- {
- memset(Tempfgets, 0, MAX_ROW_LEN);
- memset(tar, -1, sizeof(tar));
- char txtPath[260];
- int sumtat,currow,i,j;
- int fgetrow = 0;
- printf("请输入文件路径:");
- scanf("%s", txtPath);
- printf("请输入单词总数(<%d):", MAX_TarStr);
- scanf("%d", &sumtat);
- printf("依次输入查询单词:\n");
- for (int i = 0; i < sumtat; i++)
- scanf("%s", tar[i].word);
- FILE* fp = fopen(txtPath, "r");
- if (fp == NULL)
- return 0;
- while (fgets(Tempfgets, MAX_ROW_LEN, fp) != NULL)
- FindStr(Tempfgets, tar, sumtat, ++fgetrow);
- fclose(fp);
- for (i = 0; i < sumtat; i++) {
- currow = -1;
- if (tar[i].count + 1 != 0)
- printf("%s共出现%d次,其中: ", tar[i].word, tar[i].count + 1);
- else {
- printf("%s共出现0次\n", tar[i].word);
- continue;
- }
- for (j = 0; j < tar[i].pospos + 1; j++) {
- if (currow != tar[i].position[j].row) {
- if (j > 0)
- printf("\b列处出现该字符串");
- currow = tar[i].position[j].row;
- printf("\n\t第%d行中第", currow);
- }
- printf("%d,", tar[i].position[j].column + 1);
- }
- printf("\b列处出现该字符串\n");
- }
- return 0;
- }