C语言字符串排序

函数 ReadDat()实现从文件 IN.DAT 中读取一篇英文文章存入到字符串数组 xx 中,请编制函数 SortCharD(),其函数的功能是:以行为单位对字符按从大到小的顺序进行排序,排序后的结果仍按行重新存入字符串数组 xx 中,后调用函数 writeDat()把结果 xx 输出到文件 OUT2.DAT 中。
例:原文:dAe,BfC
CCbbAA
结果:fedCBA

      bbCCAA

原始数据文件存放的格式是:每行的宽度均小于 80 个字符,含标点符号和空格。
#include <stdio.h>

#include <string.h>

#include <conio.h>

char xx[50][80];

int maxline=0;/文章的总行数/

int ReadDat(void);

void WriteDat(void);

void SortCharD(void)

{int i,j,k,strl;

char ch;

for(i=0;i<maxline;i++)

{strl=strlen(xx[i]);

for(j=0;j<strl-1;j++)

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

if(xx[i][j]<xx[i][k])

{ch=xx[i][j]; xx[i][j]=xx[i][k]; xx[i][k]=ch;}

}

}

void main()

{

clrscr();

if(ReadDat()){

printf(“数据文件 IN.DAT 不能打开!\n\007”);

return;

}

SortCharD();

WriteDat();

}

int ReadDat(void)

{

FILE *fp;

int i=0;

char *p;

if((fp=fopen(“IN.DAT”,“r”))==NULL) return 1;

while(fgets(xx[i],80,fp)!=NULL){

p=strchr(xx[i],’\n’);

if§*p=0;

i++;

}

maxline=i;

fclose(fp);

return 0;

}

void WriteDat(void)

{

FILE *fp;

int i;

fp=fopen(“OUT2.DAT”,“w”);

for(i=0;i<maxline;i++){

printf("%s\n",xx[i]);

fprintf(fp,"%s\n",xx[i]);

}

fclose(fp);

}

发布了239 篇原创文章 · 获赞 3 · 访问量 3150

猜你喜欢

转载自blog.csdn.net/it_xiangqiang/article/details/105176877