c语言空字符串的排序问题

   2024-10-02 5940
核心提示:在C语言中,可以使用strcmp函数对字符串进行排序。strcmp函数比较两个字符串的大小,并返回一个整数值,如果返回值小于0,则表示

在C语言中,可以使用strcmp函数对字符串进行排序。strcmp函数比较两个字符串的大小,并返回一个整数值,如果返回值小于0,则表示第一个字符串比第二个字符串小;如果返回值等于0,则表示两个字符串相等;如果返回值大于0,则表示第一个字符串比第二个字符串大。

下面是一个示例代码,对字符串数组进行排序:

#include <stdio.h>#include <string.h>int main() {    char strings[5][20] = {"apple", "banana", "cat", "dog", "elephant"};    // Sort the strings    for (int i = 0; i < 5; i++) {        for (int j = i + 1; j < 5; j++) {            if (strcmp(strings[i], strings[j]) > 0) {                char temp[20];                strcpy(temp, strings[i]);                strcpy(strings[i], strings[j]);                strcpy(strings[j], temp);            }        }    }    // Print the sorted strings    for (int i = 0; i < 5; i++) {        printf("%s\n", strings[i]);    }    return 0;}

以上代码会对字符串数组进行排序,输出结果为:

applebananacatdogelephant

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号