【问题标题】:Count the occurrences of every word in C计算C中每个单词的出现次数
【发布时间】:2021-04-19 20:04:58
【问题描述】:

我要统计这个小文字“心碎的心碎”每一个字出现的次数。

此文本的每个单词都是 2d array[100][20],其中 100 是 max_words,20 是 max_word_length。我有一个指针array[100],其中每个指针都指向这个词。我找不到一个聪明的方法来计算相同的单词, 例如

a: 2 times
broken: 2 times
heart: 1 time
mind: 1 time
. : 1 time

这些将是指针和单词数组:

POINTERS ARRAY                      WORDS ARRAY
point0(points "a")                  a
point1(points "broken")             broken
point2(points "heart")              heart
point3(points "of")                 of
point4 (points "a")                 mind
point5(points "broken")             .
point6(points "mind")               \0\0\0\0\0
point7(points ".")                  \0\0\0\0\0
NULL                                ..
NULL
..
NULL                                \0\0\0\0\0

旁注:每个单词都是小写的。

void frequence_word(char *pointers[], int frequence_array[]) {
  int word = 0;
  int i;
  int count = 1;
  int check[MAX_WORDS];

  for (word = 0; word < MAX_WORDS; word++) {
    check[word] = -1;
  }

  for (word = 0; word < MAX_WORDS; word++) {
    count = 1;

    for (i = word + 1; i < MAX_WORDS; i++) {

      if (pointers[word + 1] != NULL
          && strcmp(pointers[word], pointers[i]) == 0) {
        count++;
        check[i] = 0;
      }

    }
    if (check[word] != 0) {
      check[word] = count;
    }

  }
}

有什么想法吗?

【问题讨论】:

  • 您好,欢迎来到堆栈溢出!为了让我们回答您的问题,您能否向我们展示一下您到目前为止所做的尝试?另外,我不认为我理解你的第二段......这是什么意思?
  • @PedroMartinsdeSouza :他的第二段是他的指针列表。编辑的时候才发现:)
  • 谢谢!我是新人,我不知道如何处理它!
  • 我没有看到指针数组的点。 char *pointers[][2]为什么第二维是2?
  • 是的,我会擦除,但我需要在另一个步骤中使用它。

标签: c counting word-processor


【解决方案1】:

这似乎是strstr 的一个用例。您可以调用strstr,然后迭代地重新分配给原始字符串,直到达到NULL。

const char substring[] = "A broken heart of a broken mind";
const char* total = ...;

const char* result;
long count = 0;
while (result = strstr(total, substring)) {
    count++;
    total += (sizeof(substring) - 1);
}

我认为这主要是不言自明的,但我将解释这一行:

total += (sizeof(substring) - 1);

它利用数组上的sizeof 返回数组长度这一事实。因此,字符数组上的 sizeof 返回其中的字符数。我们减一以忽略空终止符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多