指標陣列練習排列字串

zhongta發表於2024-05-20

用指標陣列實現排列字串

#include<stdio.h>
#include<math.h>
#include<string.h>
#define N 5
void OrderString(char *p[],int n);


int main(){
    char *arr[10]={"Hello","How are you?","I'm fine","I love computer",
    "Please sit down","Are you OK?","Build messages","Code Block","Java language","CppCheck"};

    printf("before order:\n");
        for(int i=0;i<10;i++)
        puts(arr[i]);

    OrderString(arr,10);

    printf("after order:\n");
    for(int i=0;i<10;i++)
        puts(arr[i]);
}

void OrderString(char *p[],int n){
    int i=0,j=0;
    for(;i<n-1;i++){
        for(j=i+1;j<n;j++){
                if(strcmp(p[i],p[j])>0){
                    char *temp=p[i];p[i]=p[j];p[j]=temp;
                }

        }
    }
}

相關文章