字符串排序 不知道咋存这些数据
字符串排序题目描述
输入3个字符串,按字典序从小到大进行排序。
输入
输入数据 有一行,分别为3个字符串,用空格分隔。
输出
输出排序后的三个字符串,用空格分隔。
示例输入
abcd cdef bcde
示例输出
abcd bcde cdef
程序代码:
root@~ #cat 1.c
#include <stdio.h>
struct string {
char str[10];
};
int main (void) {
struct string array[3];
int cmpstr (char s1[],char s2[]);
void cpstr (char dest[],char source[]);
char a[10],b[10],c[10],tmp[10];
int i,j,n;
for(i=0;i<3;i++) {
scanf ("%s",array[i].str);
}
printf ("Before sorted ...\n");
for (i=0;i<3;i++) {
printf ("%s ",array[i].str);
}
printf ("\n\n\n");
for(i=0;i<2;i++) {
for(j=i+1;j<3;j++) {
n=cmpstr(array[i].str,array[j].str);
if(n==1) {
cpstr(tmp,array[i].str);
cpstr(array[i].str,array[j].str);
cpstr(array[j].str,tmp);
}
}
}
printf ("After sorted...\n");
for(i=0;i<3;i++) {
printf ("%s ",array[i].str);
}
printf ("\n");
return 0;
}
//compare string1 and string2
int cmpstr (char s1[],char s2[]) {
int i=0;
while(s1[i]!='\0'&&s2[i]!='\0') {
if(s1[i]>s2[i]) {
return 1;
}
if(s1[i]<s2[i]) {
return -1;
}
i++;
}
if(s1[i]=='\0'&&s2[i]=='\0') {
return 0;
}
}
//copy string from source to destination
void cpstr (char dest[],char source[]) {
int i;
for(i=0;source[i]!='\0';i++) {
dest[i]=source[i];
}
dest[i]='\0';
}
root@~ #
