[英]How to read an unknown number of strings and how to sort the strings ordering by length and print in C
这是我写的,我真的不知道如何确定 line[??][MAXLINE]...
重点是:
所以如果我输入
I love you
me
too
结果:
me
too
I love you
#include <stdio.h>
#include <string.h>
#include "copy.h"
char line[MAXLINE][MAXLINE];
char tmp[MAXLINE];
int main () {
int len,i,j,k=0;
while(gets(line)!= NULL){
i++;//using index
len=i+1;//save i till null cuz I expect that it could be number of inputs
}
for(j=0; j< len-1; j++){
for(k=j+1; k<len-j-1; k++){
if (strlen(line[j])>strlen(line[k])){
copy(line[j],tmp);
copy(line[j],line[k]);
copy(tmp,line[k]);
}
}
}
for(j=0; j<len;j++){
printf("%s\n",line[j]);
}
printf("\n");
return 0;
}
copy.h
#define MAXLINE 100
void copy(char from[], char to[]);
copy.c
#include <stdio.h>
void copy(char from[], char to[])
{
int i;
i=0;
while ((to[i]=from[i]) != '\0')
++i;
}
使用 function strlen()
然后使用其中一种排序算法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.