题目:字符串排序。

程序分析:使用字符串比较函数strcmp()进行字符串的比较,并使用字符串拷贝函数strcpy()进行字符串的交换。

实例

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

void swap(char *str1, char *str2);

int main() {
    char str1[20], str2[20], str3[20];

    printf("请输入3个字符串,每个字符串以回车结束:\n");
    fgets(str1, sizeof(str1), stdin);
    fgets(str2, sizeof(str2), stdin);
    fgets(str3, sizeof(str3), stdin);

    if (strcmp(str1, str2) > 0)
        swap(str1, str2);
    if (strcmp(str2, str3) > 0)
        swap(str2, str3);
    if (strcmp(str1, str2) > 0)
        swap(str1, str2);

    printf("排序后的结果为:\n");
    printf("%s%s%s", str1, str2, str3);

    return 0;
}

void swap(char *str1, char *str2) {
    char temp[20];
    strcpy(temp, str1);
    strcpy(str1, str2);
    strcpy(str2, temp);
}

在上述代码中,我们使用了字符串比较函数strcmp()和字符串拷贝函数strcpy()

首先,我们定义了3个字符数组 str1str2str3,用于存储输入的3个字符串。

然后,我们使用fgets()函数从标准输入中读取字符串,并将其存储到相应的字符数组中。

接下来,我们使用strcmp()函数进行字符串的比较,如果字符串的顺序不正确,则调用swap()函数进行交换。

最后,我们使用printf()函数输出排序后的结果。

以上实例运行时,会根据输入的3个字符串进行排序,并输出排序后的结果。例如,输入字符串 "b"、"a"、"t",则输出结果为:

a
b
t

程序通过比较字符串的顺序进行排序,并使用字符串拷贝函数进行交换,以达到字符串排序的目的。

标签: c语言, c语言教程, c语言技术, c语言学习, c语言学习教程, c语言下载, c语言开发, c语言入门教程, c语言进阶教程, c语言高级教程, c语言面试题, c语言笔试题, c语言编程思想, c语言练习, c语言练习题