繁体   English   中英

如何读取未知数量的字符串以及如何按长度排序字符串并在 C 中打印

[英]How to read an unknown number of strings and how to sort the strings ordering by length and print in C

这是我写的,我真的不知道如何确定 line[??][MAXLINE]...

重点是:

  1. 从标准输入(键盘)获取输入,但我不知道输入的数量
  2. 必须使用 copy()
  3. 按字符串长度排序(从短到长!

所以如果我输入

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM