急~~C programming Problem(10 分)

2006-11-30 9:55 pm
我想問如果要係一個file 到讀裡面d 英文字(用fopen),例如:boy apple cats applied babies, 然後再將佢地 alphabetically咁排列(好似字典咁)同埋眾數既字要變返為單數, 即係上面d 字既排列會變為
apple
apply
baby
boy
cat

咁應該點寫(要用array....)??

回答 (3)

2006-12-01 12:23 am
✔ 最佳答案
有個建議,用Node。Node的結構是
struct Node {
char* word;
Node* next;
};

首先讀取檔案前設定了一個長度是26的pointer array。
Node *aryAlpha[26];
然後每讀一個字串便依它的字母排列在指定的array位置。
在加入位置前以bubble sort模式校對字串尋找識當位置並且插入字串(如要求不高,可順次序比較和插入字串)。
最後,大概那個array內容如下:
aryAlpha[0] -> "apple" -> "apply" -> null
aryAlpha[1] -> "baby" -> "boy" -> null
aryAlpha[2] -> "cat" -> null
....
aryAlpha[25] -> "zoo" -> null

然後用for loop 列出每一個array的位置直至顯示該pointer指的是null。
for (i = 0; i < 26; i++) {
for (ptr = aryAlpha[i]; ptr != null; ptr = ptr ->prt.next) {
output(ptr->word);
}
}
2006-12-01 2:22 am
r u ok for function [ fopen ]? just implement the string sorting. post any detail if u hv any problem.
try following C code:

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

int main( )
{ char str[] = "boy apple cats applied babies";
char delims[] = " ";
char *result = NULL;
char str1[64][64];
char str2[64];
int i = 0;
int j = 0;
int k = 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++ )
printf( "%s\n", str1[j] );

return 0;
}


hope can help u
2006-11-30 9:59 pm
用Array and Bubble Sort~~

2006-11-30 16:20:19 補充:
Please refer to following webpage :http://www.java2s.com/Code/CSharp/Collections-Data-Structure/DemonstratetheBubblesort.htm


收錄日期: 2021-04-12 22:48:42
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20061130000051KK01380

檢視 Wayback Machine 備份