我想统计一下“一颗破碎的心,一颗破碎的心灵”这个小文本中每个单词的出现次数。
这篇文章的每个单词都是二维的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;
}
}
}
有什么想法吗?
这似乎是一个用例strstr https://www.cplusplus.com/reference/cstring/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
on 数组返回数组长度。因此,字符数组上的 sizeof 返回其中的字符数。我们减一以忽略空终止符。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)