题目
输入10个单词,将10个单词排序后输出。请用二维字符数组编程实现。
提示:
1.输入的一个字符串中可能存在空格,如Guo Ping
2.字符串的长度最大为80
输入输出样例:
Input sample:
world
china
new
hello
good
you
me
apple
fens
help
Output sample:
apple
china
fens
good
hello
help
me
new
world
you
吐槽
要吐槽的是,这个题很简单,我却花了很长的时间去做,原因就是卡在了思考上面
给几个有用的背景知识,字符串赋值:strcpy函数
然后字符二维数组,每一行就代表着一行字符串,有了这个思路这个题就比较好做了
自己出问题的地方出在比较函数上!
代码(已经accepted)
#include <stdio.h>
#include <string.h>
int cmp(char str1[80],char str2[80]){
int len1 = strlen(str1),len2=strlen(str2),i;
for(i=0;i<len1 &&i<len2;i++){
if(str1[i]<str2[i]){
return 1;
}
if(str1[i]>str2[i]){
return 0;
}
}
}
int main(){
char str[10][80],temp[80],min[80];
int i,j,pos;
for(i=0;i<10;i++){
gets(str[i]);
}
//printf("\n");
for(i=0;i<10;i++){
strcpy(min,str[i]);
pos=i;
for(j=i+1;j<10;j++){
if(cmp(str[j],min)==1){
// printf("过程 j %d ",j);
// printf("min %s\n",min);
strcpy(min,str[j]);
pos = j;
}
}
//cout<<"i "<<i<<" pos "<<pos<<endl;
// printf(" i %d pos %d \n",i,pos);
strcpy(temp,str[i]);
strcpy(str[i],str[pos]);
strcpy(str[pos],temp);
}
for(i=0;i<10;i++){
printf("%s\n",str[i]);
}
//printf("%d",cmp("new","china"));
return 0;
}