我正在尝试计算struct的动态数组中单词的出现次数。但输出与所需答案不匹配。任何对代码的指导或修改都将不胜感激。
void COUNT(struct wordsStruct *allWords, int size)
{
int boolean = 0;
int count = 0;
for (int i = 0; i < size; i++)
{
count = 0;
for (int j = i + 1; j < size; j++)
{
printf("Comparing %s with %s \n", (allWords[i].name, allWords[j].name));
if (strcasecmp(allWords[i].name, allWords[j].name) == 0)
{
boolean = 1;
count++;
}
else
{
boolean = 0;
}
}
if (boolean == 1 && count != 0)
{
allWords[i].number = count;
}
}
}
int main(int argc, char** argv)
{
// Declaring Variables
FILE *fileReader;
int numberOfWords;
struct wordsStruct *container;
if (argc == 1)
{
printf("More Arguments Needed. \n");
}
else if (argc == 2)
{
numberOfWords = SCAN(&fileReader, argv[1]);
printf("Number Of Words: %d. \n", numberOfWords);
container = LOAD(fileReader, numberOfWords, argv[1]);
qsort(container, numberOfWords, sizeof(struct wordsStruct), compare);
COUNT(container, numberOfWords);
for (int i=0; i<numberOfWords; i++)
{
printf("WORD: %s. \t", container[i].name);
printf("Occurence: %d. \n", container[i].number);
}
}
return (0);
}
typedef struct wordsStruct
{
char* name;
int number;
}wordsStruct;
//INPUT FILE
My
Code
ZZZ
ZZZ
Is
Not
zzz
ZZZ
zzz
Working
//Output
WORD: Code. Occurence: 1.
WORD: Is. Occurence: 1.
WORD: My. Occurence: 1.
WORD: Not. Occurence: 1.
WORD: Working. Occurence: 1.
WORD: Working. Occurence: 1.
WORD: zzz. Occurence: 4.
WORD: ZZZ. Occurence: 3. // THIS SHOULD BE 5?
WORD: zzz. Occurence: 2.
WORD: ZZZ. Occurence: 1.
WORD: ZZZ. Occurence: 1.
答案 0 :(得分:1)
您错误地断定strcasecmp
无效。
您的代码中存在一些逻辑错误。
for (int j = i + 1; j < size; j++)
{
printf("Comparing %s with %s \n", (allWords[i].name, allWords[j].name));
if (strcasecmp(allWords[i].name, allWords[j].name) == 0)
{
boolean = 1;
count++;
}
else
{
boolean = 0;
}
}
上面的代码块有:
i
处的单词不匹配,则会将boolean
设置为0
,用于检查是否找到匹配项或不试试这个:
for (int i = 0; i < size; i++)
{
count = 0;
int j;
for ( j = i + 1; j < size; j++)
{
printf("Comparing %s with %s \n", (allWords[i].name, allWords[j].name));
if (strcasecmp(allWords[i].name, allWords[j].name) == 0)
{
boolean = 1; // Don't need this at all.
count++;
}
else
{
break;
}
}
if (count != 0)
{
allWords[i].number = count;
}
// If there are three matching words, j would be i + 3;
// We don't need to compare the words at i+1, i+2 again.
// Change i to be the index of the next word for comparison.
i = j-1;
}
<强>更新强>
关于
的部分allWords[i].number = count;
需要更好。
for (int i = 0; i < size; i++)
{
// The count is at least 1
count = 1;
int j;
for ( j = i + 1; j < size; j++)
{
printf("Comparing %s with %s \n", (allWords[i].name, allWords[j].name));
if (strcasecmp(allWords[i].name, allWords[j].name) == 0)
{
boolean = 1; // Don't need this at all.
count++;
}
else
{
break;
}
}
for ( ; i < j; ++i )
{
allWords[i].number = count;
}
}