超超急!!!!!!!!C programming question

2006-12-04 8:45 am
我想問如果係一個file read 左d 字返黎, 又順序排列好晒(即alphabetically), 點樣可以check 到佢地發生過幾多次, 同only print out 果個字1 次????

例如: 讀返黎既字有{apple, boy,boy, cat, cat ,cat,}
print out 既樣就要好似下面咁:
apple 1
boy 2
cat 3


Could anyone tell me how to code them ???

回答 (2)

2006-12-07 6:11 pm
✔ 最佳答案
r u ok for process to read text from a file? just implement for sorting and counting code. please check

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

int main( )
{ char str[] = "apple,apple,boy,boy,boy,boy,boy,cat,cat,cat";
char delims[] = ",";
char *result = NULL;
char str1[64][64];
char str2[64];
int i = 0;
int j = 0;
int k = 0;
int cnt = 0;

result = strtok( str, delims );

while( result != NULL )
{ strcpy( str1[i], result );
i++;
result = strtok( NULL, delims );
}

for ( j = 0; j < i; j++ )
for ( k = 0; k < i - 1; k++ )
if ( strcmp( str1[k], str1[k+1] ) >= 0 )
{ strcpy( str2, str1[k+1] );
strcpy( str1[k+1], str1[k] );
strcpy( str1[k], str2 );
}
for ( j = 0; j < i; j++ )
{ if ( j == 0 ) // initial string
strcpy( str2, str1[0] );
if ( strcmp( str2, str1[j] ) == 0 )
cnt ++;
else
{ printf( "%s - %d\n", str2, cnt );
strcpy( str2, str1[j] );
cnt = 1;
}
}

printf( "%s - %d\n", str2, cnt );

return 0;
}


hope can help u
2006-12-04 8:10 pm
Here it is, post if you have questions.
Cheers.

/* sort.c merges a list of words */
#include
#include
#include
int main(int argc, char *argv[]){
char* list[]={&quot;apple&quot;,&quot;boy&quot;,&quot;boy&quot;,&quot;cat&quot;,&quot;cat&quot;,&quot;cat&quot;};
int len=6;
int n=0,i;
char last[200]=&quot;&quot;;
for(i=0;i &lt; len ;i++){
if(strcmp(last,list[i])){
if( i &gt; 0 )printf(&quot;%s %d\n&quot;,last,n);
n=1;
strcpy(last,list[i]);
} else {
n++;
}
}
printf(&quot;%s %d\n&quot;,last,n);
return 0;
}


收錄日期: 2021-04-12 20:08:50
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20061204000051KK00187

檢視 Wayback Machine 備份