gpt4 book ai didi

c - 找到出现次数较多的字符串(单词)

转载 作者:行者123 更新时间:2023-11-30 15:40:59 27 4
gpt4 key购买 nike

我必须给一个数字x,并写x个字符串(单词)。我必须找到写得最多的那一篇。它可以工作,但是当我尝试从文件中读取它时,却没有。例如,如果我执行 a.out''<'file 并且文件如下:

  1. 5
  2. 你好
  3. 世界
  4. 你好
  5. 好的

所有这些都在不同的行中,每个字符串在不同的行中它都可以工作,并且我打印你好,但是如果很多字符串像文本一样在一行中,它就不会工作(hello yes word hello e.t.c...

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

int main(void)
{
char **str;
int n,i,j,y;
int count=0;
printf("Give a nubmer : \n");
scanf("%d", &n);
str = (char **)malloc(n *(sizeof(50)));
for(i=0; i<n+1; i++)
str[i] = (char *)malloc(50);
printf("Give n strings : \n");
for(i=0; i<n+1; i++)
{
gets(str[i]);
}
for(i=0; i<n+1; i++)
{
for (j=i+1;j<n+1;j++)
{
if(strcmp(str[i],str[j])==0)
{
count++;
// i++;
y=i;
}
}
}
printf("\n%s\n",str[y]);
}

这是我使用 gets 而不是 fgets 的问题吗?

最佳答案

考虑以下因素:

#define NUM_STRINGS (10)

int strListCompare(const void *p1, const void *p2)
{
const char **str1 = p1;
const char **str2 = p2;
return strcmp(*str1, *str2);
}

int main(void)
{
char *strList[NUM_STRINGS] = {
"dog", "cat", "cat", "bat", "cat",
"cat", "dog", "bat", "dog", "bat"
};

qsort(strList, NUM_STRINGS, sizeof(char *), strListCompare);

char *curStr = strList[0], *maxStr = strList[0];
int curCount = 0, maxCount = 0;

for(int i = 0; i < (NUM_STRINGS - 1); i++)
{
curCount++;

if((strcmp(strList[i], strList[i + 1]) != 0) && (curCount > maxCount))
{
maxCount = curCount;
maxStr = strList[i];
curCount = 0;
}
}

printf("The winner! \"%s\" (%d occurrences)\n", maxStr, maxCount);
return 0;
}

执行上述程序会产生以下输出:

The winner! "cat" (4 occurrences)

这是逻辑:

At first, strList is not sorted. I sort it to aid in determining the string that occurs the most. Before I scan strList, I assume the first element will be the most occurring string. Now, I scan strList and count occurrences. If the next string is the same as the current string, I increment curCount. As soon as the next string is not the same as the current string, I compare curCount to maxCount. If curCount is greater than maxCount, I've found a new string that occurs the most often. I set curCount and the current string to maxCount and maxStr respectively. When the loop ends, maxCount and maxStr will the have the string that occurs the most.

关于c - 找到出现次数较多的字符串(单词),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20725784/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com