C語言字符串左右排序交換

函數 ReadDat()實現從文件 in.dat 中讀取 20 行數據存放到字符串數組 xx 中(每行字符串長 度均小於 80)。

請編制函數 jsSort(),其函數的功能是:以行爲單位對字符串按給定的條件進 行排序,排序後的結果仍按行重新存入字符串數組 xx 中,後調用函數 WriteDat()把結果 xx 輸出到文件 out.dat 中。

條件:從字符串中間一分爲二,左邊部分按字符的 ASCII 值升序排序,排序後左邊部 分與右邊部分進行交換。

如果原字符串長度爲奇數,則中間的字符不參加處理,字符仍放 在原位置上。

例如:位置 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 中。

請勿改動主函數 main()、讀函數 ReadDat()和寫函數 WriteDat()的內容。

#include <stdio.h>

#include <string.h>

#include <conio.h>

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;j<half-1;j++)

for(k=j+1;k<half;k++)

if(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=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);

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章