★題目50(無憂id 2 字符串左右排序交換題 )
函數(shù)ReadDat()實現(xiàn)從文件in.dat中讀取20行數(shù)據(jù)存放到字符串數(shù)組xx中(每行字符串長度均小于80)。請編制函數(shù)jsSort(),其函數(shù)的功能是:以行為單位對字符串按給定的條件進行排序,排序后的結果仍按行重新存入字符串數(shù)組xx中,最后調用函數(shù)WriteDat()把結果xx輸出到文件out.dat中。
條件:從字符串中間一分為二,左邊部分按字符的ASCII值升序排序,排序后左邊部分與右邊部分進行交換。如果原字符串長度為奇數(shù),則最中間的字符不參加處理,字符仍放在原位置上。
例如:位置 0 1 2 3 4 5 6 7 8
源字符串 d c b a h g f e
4 3 2 1 9 8 7 6 5
則處理后字符串 h g f e a b c d
8 7 6 5 9 1 2 3 4
部分源程序存在文件prog1.c中。
請勿改動主函數(shù)main()、讀函數(shù)ReadDat()和寫函數(shù)WriteDat()的內容。
#include
#include
#include
char xx[20][80];
void jsSort()
{ int i,j,k,strl,half;
char temp;
for(i=0;i<20;i++)
{ strl=strlen(xx[i]);
half=strl/2;
for(j=0;jfor(k=j+1;kif(xx[i][j]>xx[i][k])
{ temp=xx[i][j]; xx[i][j]=xx[i][k]; xx[i][k]=temp;}
for(j=half-1,k=strl-1;j>=0;j--,k--)
{ temp=xx[i][j]; xx[i][j]=xx[i][k]; xx[i][k]=temp;}
}
}
void main()
{
readDat();
jsSort();
writeDat();
}
readDat()
{
FILE *in;
int i=0;
char *p;
in=fopen("in.dat","r");
while(i<20 && fgets(xx[i],80,in)!=NULL){
p=strchr(xx[i],'\n');
if(p) *p=0;
i++;
}
fclose(in);
}
writeDat()
{
FILE *out;
int i;
clrscr();
out=fopen("out.dat","w");
for(i=0;i<20;i++){
printf("%s\n",xx[i]);
fprintf(out,"%s\n",xx[i]);
}
fclose(out);
}
函數(shù)ReadDat()實現(xiàn)從文件in.dat中讀取20行數(shù)據(jù)存放到字符串數(shù)組xx中(每行字符串長度均小于80)。請編制函數(shù)jsSort(),其函數(shù)的功能是:以行為單位對字符串按給定的條件進行排序,排序后的結果仍按行重新存入字符串數(shù)組xx中,最后調用函數(shù)WriteDat()把結果xx輸出到文件out.dat中。
條件:從字符串中間一分為二,左邊部分按字符的ASCII值升序排序,排序后左邊部分與右邊部分進行交換。如果原字符串長度為奇數(shù),則最中間的字符不參加處理,字符仍放在原位置上。
例如:位置 0 1 2 3 4 5 6 7 8
源字符串 d c b a h g f e
4 3 2 1 9 8 7 6 5
則處理后字符串 h g f e a b c d
8 7 6 5 9 1 2 3 4
部分源程序存在文件prog1.c中。
請勿改動主函數(shù)main()、讀函數(shù)ReadDat()和寫函數(shù)WriteDat()的內容。
#include
#include
#include
char xx[20][80];
void jsSort()
{ int i,j,k,strl,half;
char temp;
for(i=0;i<20;i++)
{ strl=strlen(xx[i]);
half=strl/2;
for(j=0;jfor(k=j+1;kif(xx[i][j]>xx[i][k])
{ temp=xx[i][j]; xx[i][j]=xx[i][k]; xx[i][k]=temp;}
for(j=half-1,k=strl-1;j>=0;j--,k--)
{ temp=xx[i][j]; xx[i][j]=xx[i][k]; xx[i][k]=temp;}
}
}
void main()
{
readDat();
jsSort();
writeDat();
}
readDat()
{
FILE *in;
int i=0;
char *p;
in=fopen("in.dat","r");
while(i<20 && fgets(xx[i],80,in)!=NULL){
p=strchr(xx[i],'\n');
if(p) *p=0;
i++;
}
fclose(in);
}
writeDat()
{
FILE *out;
int i;
clrscr();
out=fopen("out.dat","w");
for(i=0;i<20;i++){
printf("%s\n",xx[i]);
fprintf(out,"%s\n",xx[i]);
}
fclose(out);
}