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);

}

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