计算相同和重复单词的数量

时间:2013-09-28 16:58:36

标签: c

我的代码计算给定字符串上的关键字数量,但我需要将重复的关键字计为1并将其计为唯一关键字。有人请帮助我,我无法弄清楚我会怎么做:( 。请?

#include <stdio.h>
#include <string.h>

int main()
{
  char string[] = "\nauto else else do while >> \nfor 1+2 == goto";
  char *keywords[] =
  { "auto", "break", "else", "case", "if" };
  int s = 0, i, x = 1;
  char *result;
  char delims[] = "  \n";
  int keyword = 0, ukeyword = 0;

  printf("Input: %s", string);
  //Count the number of lines
  for (i = 0; string[i] != '\0'; ++i)
  {
    if (string[i] == '\n')
      ++s;
  }
  printf("\n\nNo. of lines: %d", s);

  result = strtok(string, delims);
  while (result != NULL )
  {
    for (x = 0; x != 5; x++)
    {
      if (strcmp(result, keywords[x]) == 0)
      {
        keyword++;
      }
    }

    result = strtok(NULL, delims);
  }

  printf("\nNo. of keywords: %d.\n", keyword);
  printf("\nNo. of unique keywords: %d.\n", ukeyword);
  return 0;
}

所以输出应该是:

Input:
auto else else do while >>
for 1+2 == goto

No. of lines:2
No. of keywords:3
No. of unique keywords:2

2 个答案:

答案 0 :(得分:2)

您必须单独计算每个关键字的出现次数:

int keyword_count[5];

当你找到一个关键词时,你必须增加一个相应的计数器:

keywords ++;
keyword_count[x] ++;

最后,唯一关键字是具有keyword_count [x] == 1

的关键字

答案 1 :(得分:0)

#include <stdio.h>
#include <string.h>

int totalKeywords, uniqueKeywords;

struct keywordStruct
{
    char *keyword;
    int count = 0;
} keywords[5];

void updateKeywordCount(char word[]) {
    int i = 0;
    for (; i < sizeof(keywords)/sizeof(keywordStruct); i++) {
        if (strcmp(keywords[i].keyword, word) == 0) {
            if (keywords[i].count == 0) {
                uniqueKeywords += 1;
                keywords[i].count = 1;
            }
            totalKeywords += 1;
            return;
        }
    }
}

int main(int argc, char const *argv[])
{
    char word[100], currentChar;
    int i, lines = 0, charInWordCount = 0;
    keywords[0].keyword = "auto";
    keywords[1].keyword = "break";
    keywords[2].keyword = "else";
    keywords[3].keyword = "cause";
    keywords[4].keyword = "if";
    freopen("Input.txt", "r", stdin);
    while (scanf("%c", &currentChar) == 1) {
        if (currentChar == '\n' || currentChar == '\r') {
            lines += 1;
            word[charInWordCount++] = '\0';
            charInWordCount = 0;
            updateKeywordCount(word);
        } else if (currentChar == ' ') {
            word[charInWordCount++] = '\0';
            charInWordCount = 0;
            updateKeywordCount(word);
        } else {
            word[charInWordCount++] = currentChar;
        }
    }
    if (charInWordCount) {
        lines += 1;
        word[charInWordCount++] = '\0';
        updateKeywordCount(word);
    }
    printf ("No. of lines: %d\n", lines);
    printf ("No. of keywords: %d\n", totalKeywords);
    printf ("No. of unique keywords: %d\n", uniqueKeywords);
    return 0;
}

<强>输出

No. of lines: 2
No. of keywords: 3
No. of unique keywords: 2