如何调用函数进行数组内字符串的排序

调用函数后的结果不知道应该怎么返回并且打印出来 程序运行只能显示排序前的结果

在排序函数中,可以把字符串数组作为参数传入函数进行排序,排序后的结果就可以主函数中显示,下面是一个测试例子,供参考:

参考链接:
strcmp函数详解看这一篇就够了-C语言(函数实现、使用用法举例、作用、与strncmp的区别)_嘎嘎烤鸭的博客-CSDN博客_strcmp

#include <stdio.h>
#include <string.h>
#define MAX 20

void sort(char strs[][MAX],int n){
    
    int i,j;
    char temp[MAX];
    
    for(i=0;i<n;i++){
        for(j=i;j<n;j++){
            //  https://blog.csdn.net/m0_65601072/article/details/123991662
            if(strcmp(strs[i],strs[j])>0){  // 按字符串ASCII码值升序排序 
                strcpy(temp,strs[i]);
                strcpy(strs[i],strs[j]);
                strcpy(strs[j],temp);
            }
        }
    }
    
    
} 


int main(void){
    
    char strs[5][MAX] = {"ABCDEDG","xyz is end","book on the desk","student like study","good day"};
    int i;
    printf("排序前,数组的字符串如下:\n");
    for(i=0;i<5;i++){
        printf("%s\n",strs[i]); 
    }
    
    sort(strs,5);
    
    printf("排序后,数组的字符串如下:\n");
    for(i=0;i<5;i++){
        printf("%s\n",strs[i]); 
    }
}

img



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

int main()
{

   char *str[3] = {"abcde", "12345", "67890123"};
   order(str, 3);

   for (int i = 0; i < 3; i++)
      puts(str[i]);

   return 0;
}

在C语言中,可以使用qsort函数对数组进行排序。这是一个快速排序函数,可以对数组中的任何类型的元素进行排序。下面的例子完成了使用qsort函数对字符串数组进行排序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int compare_strings(const void* a, const void* b) {
const char** ia = (const char**)a;
const char** ib = (const char**)b;
return strcmp(*ia, *ib);
}

int main() {
char* arr[] = {"apple", "banana", "cherry", "date", "elderberry", "fig"};
int n = sizeof(arr) / sizeof(arr[0]);

Copy code
qsort(arr, n, sizeof(char*), compare_strings);

for (int i = 0; i < n; i++) {
    printf("%s ", arr[i]);
}
printf("\n");

return 0;
}

具体说来,我们定义了一个名为compare_strings的函数,用于比较两个字符串。然后,我们使用qsort函数对字符串数组进行排序,并将compare_strings函数作为第四个参数传递给qsort函数。最后,我们循环遍历数组并将排序后的字符串打印出来。

如果想将qsort函数的结果作为一个新的数组返回,可以使用malloc函数分配新数组的内存,并使用memcpy函数将排序后的字符串复制到新数组中。