我想問如果係一個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 ???
2006-12-03 19:45:19 · 2 個解答 · 發問者 none 2 in 電腦與網際網路 ➔ 程式設計
r u ok for process to read text from a file? just implement for sorting and counting code. please check
#include
#include
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-07 05:11:50 · answer #1 · answered by ? 6 · 0⤊ 0⤋
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[]={"apple","boy","boy","cat","cat","cat"};
int len=6;
int n=0,i;
char last[200]="";
for(i=0;i < len ;i++){
if(strcmp(last,list[i])){
if( i > 0 )printf("%s %d\n",last,n);
n=1;
strcpy(last,list[i]);
} else {
n++;
}
}
printf("%s %d\n",last,n);
return 0;
}
2006-12-04 07:10:48 · answer #2 · answered by p 6 · 0⤊ 0⤋