字符串排序

来源:互联网 发布:店铺数据查看 编辑:程序博客网 时间:2024/05/16 09:39

(1)任务描述
要求编写程序,读入5个字符串,按由小到大的顺序输出。
(2)功能要求
①输入格式:输入为由空格分隔的5个非空字符串,每个字符串不包括空格、制表符、换行符等空白字符,长度小于80。
②输出格式:
按照以下格式输出排序后的结果:
After sorted:
每行一个字符串
输入样例:
red yellow blue green white
输出样例:
After sorted:
blue
green
red
white
yellow
解析:主要掌握函数strtok函数的用法;

代码:

#include <stdio.h>
#include <string.h>
typedef struct
{
char *data;
}CHAR;
int main()
{
int i = 1, j, n;
CHAR *T;
T = (CHAR *)malloc(sizeof(CHAR) * 6);
char *s;
s = (char *)malloc(sizeof(char) * 80);
printf("输入字符串:\n");
gets(s);
char ch;
char *m = " ";//s中需要去掉的字符;
char *p;//接收提取出来的字符串
T[0].data = (char *)malloc(sizeof(char) * 6);
strcpy(T[0].data, strtok(s, m));//第一次调用要用原数组
while ((p = strtok(NULL, m)))//第二次调用要用NULL
{
T[i].data= (char *)malloc(sizeof(char) * 6);
strcpy(T[i++].data, p);//拷贝字符串
       
}
n = i;
        printf("After sorted:\n");
for (i = 0; i < 26; i++)
{
     ch = 'a' + i;
for (j = 0; j < n; j++)
if (T[j].data[0] == ch)//满足首字母最大则输出
printf("%s\n", T[j].data);
}
printf("\n");
}

原创粉丝点击