C语言 统计相同单词出现次数

必需有一个结构体 struct,然后统计相同单词出现次数。
比如 输入 ABC(空格)DEF(空格)ABC(空格)CBA(回车)
则输入ABC=2 DEF=1 CBA=1
我用的是WIN-TC
谢谢大家,请帮帮我这个菜鸟
必需有struct

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

#define MAX 100

typedef struct tagWordCounter
{
char word[20];
int count;
}WordCounter;

WordCounter wc[MAX];
int num=0;

main()
{
char wd[20];
int i;
char ch;
while(1)
{
scanf("%s",wd);
for(i=0;i<num;i++)
if(strcmp(wd,wc[i].word)==0)
{
wc[i].count++;
break;
}
if(i==num)
{
num++;
strcpy(wc[num-1].word,wd);
wc[num-1].count=1;
}
ch=getc(stdin);
if(ch==10 || ch==13)
break;
}
for(i=0;i<num;i++)
{
printf("%s=%d ",wc[i].word,wc[i].count);
}
printf("\n");
getch();
}
在WinTc下编译通过
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-08-25
#include <string.h>
#include <stdio.h>

struct NODE
{
char *pStr;
int strCount;
NODE *pNext;
};
NODE* findString(NODE *pFirst,const char *str);
void addNode(NODE *pFirst,const char *str);
void CreateNode(NODE **ppNode,const char *str);
void ReleaseNode(NODE *pNode);
int main(int argc, char* argv[])
{ "char str[] = "abc abc bbb ccc bbb ccc aaa csa fgh dd abc";
char spe[] = " \t\n";
char *toke = strtok(str,spe);
NODE *pNodeHead = NULL;
while (NULL != toke )
{
if (NULL == pNodeHead)
{
CreateNode(&pNodeHead,toke);
toke = strtok(NULL,spe);
continue;
}
NODE *pTmpNode = findString(pNodeHead,toke);
if (NULL == pTmpNode)
{
addNode(pNodeHead,toke);
}else
{
++(pTmpNode->strCount);
}
toke = strtok(NULL,spe);
}
NODE *tmp = pNodeHead;
if (NULL == pNodeHead)
{
return 1;
}
while (pNodeHead)
{
cout<<pNodeHead->pStr<<" "<<pNodeHead->strCount<<endl;
pNodeHead = pNodeHead->pNext;
}

return 0;
}

NODE* findString(NODE *pFirst,const char *str)
{
if (NULL == pFirst)
{
return NULL;
}
do
{
if (0 == strcmp(pFirst->pStr,str))
{
return pFirst;
}
}while(pFirst = pFirst->pNext);
return NULL;
}
void addNode(NODE *pNode,const char *str)
{
if (pNode == NULL)
{
return;
}
while (NULL != pNode->pNext)
{
pNode = pNode->pNext;
}
pNode->pNext = (NODE*)malloc(sizeof(NODE));
pNode = pNode->pNext;
memset(pNode,0,sizeof(NODE));
pNode->pStr = (char*)malloc(strlen(str));
strcpy(pNode->pStr,str);
++(pNode->strCount);
pNode->pNext = NULL;
return;
}
void CreateNode(NODE **ppNode,const char *str)
{
NODE *node;
node = (NODE*)malloc(sizeof(NODE));
memset(node,0,sizeof(NODE));
node->pStr = (char*)malloc(strlen(str));
strcpy(node->pStr,str);
++(node->strCount);
node->pNext = NULL;
*ppNode = node;
}

没写释放的部分,你自己加上吧。
相似回答