字符串排序只要是用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()就返回正數,反之則返回負數。