指针数组是一种灵活的存字符串的方式,使用交换排序思想对字符串进行排序
//字符串排序(数组法)
void SortStr1(char str[5][9]){
char temp[9];
int i,j;
printf("Before sorted:\n");
for(i=0;i<5;i++){
puts(str[i]);
}
for(i=0;i<4;i++){
for(j=i+1;j<5;j++){
if(strcmp(str[i],str[j])>0){//从小到大排
strcpy(temp,str[i]);
strcpy(str[i],str[j]);
strcpy(str[j],temp);
}
}
}
printf("after sorted:\n");
for(i=0;i<5;i++){
puts(str[i]);
}
}
//字符串排序(指针数组)
void SortStr2(char *ptr[5]){
char *temp=NULL;
int i,j;
printf("Before sorted:\n");
for(i=0;i<5;i++){
puts(ptr[i]);
}
for(i=0;i<4;i++){
for(j=i+1;j<5;j++){
if(strcmp(ptr[i],ptr[j])>0){
temp=ptr[i];
ptr[i]=ptr[j];
ptr[j]=temp;
}
}
}
printf("after sorted:\n");
for(i=0;i<5;i++){
puts(ptr[i]);
}
}
//main函数中字符串排序的调用
//数组方式
char str[5][9]={"zhou","jia","yu","mei","zhang"};
SortStr1(str); //注意二维数组作为函数参数的调用,这种方式是可以的
//指针方式
char *ptr[5]={"zhou","jia","yu","mei","zhang"};
SortStr2(ptr);