資源簡介
統計文件中的所有字符串出現的次數,在行尾未完的字符用"-"連接,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?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;
}
- 上一篇:MFC制作可編輯鬧鐘
- 下一篇:編譯原理消除無用產生式的文法化簡
評論
共有 條評論