題目
輸入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[],char str2[]){
int len1 = strlen(str1),len2=strlen(str2),i;
for(i=;i<len1 &&i<len2;i++){
if(str1[i]<str2[i]){
return ;
}
if(str1[i]>str2[i]){
return ;
}
}
}
int main(){
char str[][],temp[],min[];
int i,j,pos;
for(i=;i<;i++){
gets(str[i]);
}
//printf("\n");
for(i=;i<;i++){
strcpy(min,str[i]);
pos=i;
for(j=i+;j<;j++){
if(cmp(str[j],min)==){
// 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=;i<;i++){
printf("%s\n",str[i]);
}
//printf("%d",cmp("new","china"));
return ;
}