字符串排序只要是用strcmp()函数来确定两个字符串的顺序,一般的做法是读取字符串函数,排序字符串并打印出来。
输入示例
o that i was where i would be,
then would i be where i am not,
but where i am i must be,
and where i would be i can not.
输出示例
and where i would be i can not.
but where i am i must be,
o that i was where i would be,
then would i be where i am not,
程序示例
#include<stdio.h>
#include<string.h>
#define SIZE 81
#define LIM 20 /*可读入的最多行数*/
#define HALT "" /*空格字符串停止输入*/
void stsrt(char *strings[], int num);
char *s_gets(char *st, int n);
int main()
{
char input[LIM][SIZE]; /*存储输入的数组*/
char *ptstr[LIM]; /*内含指针变量的数组,均指向每一行的首地址*/
int ct = 0; /*输入计数*/
int k; /*输出计数*/
printf("input up to %d lines,and i will sort them.\n", LIM);
printf("to stop,press the enter key at a line's start.\n");
/*此处只需要直接指向字符数组某一行的首地址,便可以实现怼字符串的输入*/
while (ct < LIM&&s_gets(input[ct], SIZE) != NULL&&input[ct][0] != '\0')
{
ptstr[ct] = input[ct]; /*设置指针指向字符串*/
ct++;
}
stsrt(ptstr, ct);
puts("\nhere's the sorted list:\n");
for (k = 0; k < ct; k++)
puts(ptstr[k]); /*排序后的指针*/
return 0;
}
/*选择排序*/
/*字符串-指针-排序函数&&指针与一维数组*/
void stsrt(char *strings[], int num)
{
char *temp;
int top, seek;
for(top=0;top<num-1;top++)
for(seek=top+1;seek<num;seek++)
if (strcmp(strings[top], strings[seek]) > 0)
{
temp = strings[top];
strings[top] = strings[seek];
strings[seek] = temp;
}
}
char *s_gets(char *st, int n) /*指针与一维数组*/
{
char *ret_val;
int i = 0;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
while (st[i] != '\n'&&st[i] != '0')
i++;
if (st[i] == '\n') st[i] = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
关于strcmp()函数:
strcmp()函数比较所有的字符,不只是字母,如果 第一个字符串位于第二个字符串的前面,strcmp()就返回正数,反之则返回负数。