资源简介

统计文件中的所有字符串出现的次数,在行尾未完的字符用"-"连接,c语言编写,包括"rdline.c","abc",编译"rdline.c"后直接,运行就行,不要加参数,会自动读取"abc"中的内容。

资源截图

代码片段和文件信息

/* 统计一个文件中字符串出现的次数,字符串间出空格分隔
 *  行尾未完的字符用字符“-”连接,
 * 标点符号的左右都要求有空格
 * 注:不能处理包含中文的文件
 */


#include
#include
#include
#include

struct kv //key-value
{
char *p;
int count;
};

struct kv_head
{
int len;
struct kv *pnode;
};


struct kv_head listHead;
struct kv node[200];

int findindex(char *pwordstruct kv_head* phead)
{
int index=0;
int ret=-1;
for(index=0;index < phead->len;index++)
{
ret = strcmp(pwordphead->pnode[index].p);
if (ret == 0)
break;
}
if (ret == 0)
return index;

return -1;
}

int
main()
{
listHead.len=0;
listHead.pnode=node;


FILE *fp;
char readbuff[200];
char wordbuff[30];
char wordbuff2[30];
char *pread*p2*pend*ptmp*ptmp2;
int lenindexflag=0;
int part1len=0;
int existindex=-1;
int lentmp;

fp = fopen(“./abc““r+“);
while( !(feof(fp)) )
{
readbuff[0]=‘\0‘;
fgets(readbuff200fp);

if (readbuff[strlen(readbuff)-2] != ‘-‘)
{
lentmp=strlen(readbuff);
readbuff[strlen(readbuff)]=‘\n‘;
readbuff[lentmp-1]=‘ ‘;
readbuff[lentmp + 1]=‘\0‘;
}

pread = readbuff;
ptmp=readbuff;
ptmp2=readbuff;

while(*pread == ‘ ‘ || *pread == ‘\t‘)
pread++;

#if 1
if (flag == 1)
{
p2=pread;
pread=strchr(pread‘ ‘);
memcpy(wordbuff + part1lenp2pread-p2);
*(wordbuff+part1len+ (pread-p2)) = ‘\0‘;

if ((existindex = findindex(wordbuff&listHead)) >= 0)
{
listHead.pnode[existindex].count++;
existindex = -1;
goto out1;
}

listHead.pnode[listHead.len].p=(char *)malloc(strlen(wordbuff) + 1);
memcpy(listHead.pnode[listHead.len].pwordbuffstrlen(wordbuff));
*(listHead.pnode[listHead.len].p + strlen(wordbuff))=‘\0‘;
listHead.pnode[listHead.len].count=1;

listHead.len++;
out1:
while(*pread == ‘ ‘)
pread++;
// pread+=1;

}

if ((ptmp = strrchr(ptmp‘-‘)) != NULL)
{
pend=strrchr(ptmp2‘ ‘);
flag=1;
memcpy(wordbuffpend+1ptmp-pend-1);
part1len = ptmp-pend-1;
}
else
flag=0;
///temp end;

p2 = pread;
while ((pread=strchr(pread‘ ‘)) != NULL)
{
len = pread - p2;
memcpy(wordbuff2p2len);
wordbuff2[len]=‘\0‘;

if ((existindex = findindex(wordbuff2&listHead)) >= 0)
{
listHead.pnode[existindex].count++;
existindex = -1;
goto out2;
}

listHead.pnode[listHead.len].p=(char *)malloc(len * sizeof(char) + 1);
memcpy(listHead.pnode[listHead.len].pp2len);
*(listHead.pnode[listHead.len].p + len)=‘\0‘;
listHead.pnode[listHead.len].count=1;

listHead.len++;
out2:
// p2 = pread + 1;
// pread+=1;
while(*pread == ‘ ‘)
pread++;
p2=pread;
}

#endif


}

index = 0;
while (index  {
printf(“word %d :%s\t%d\n“indexlistHead.pnode[index].plistHead.pnode[index].count);
index++;
}


return 0;
}

评论

共有 条评论