C语言经典例79-字符串排序

1 题目

字符串排序,输出三个字符串(长度小于20),并将其按照ASCII码顺序排序。

2 分析

首先限制三个字符串的输入,本例利用fgets函数,该函数的原型为:

char *fgets(char *str, int n, FILE *stream)
  • str : 这是指向一个字符数组的指针,该数组存储了要读取的字符串。
  • n : 这是要读取的最大字符数(包括最后的空字符)。通常是使用以 str 传递的数组长度。
  • stream : 这是指向 FILE 对象的指针,该 FILE 对象标识了要从中读取字符的流。

其中字符串的长度可以通过sizeof技巧来计算即数组总大小/单个项大小,就是总长度sizeof str1 / sizeof str1[0],stream则为标准输入流stdin

由于本例中只有三个字符串,很容易想到之前做过的三个数的大小比较, 是通过三个if语句判断的,在本例中如何判断字符串大小呢?实际上C语言string.h头文件中包含了字符串比较函数strcmp,它的函数原型如下:

int strcmp(const char *str1, const char *str2)

其中str1str2是要比较的两个字符串,它的返回值如下:

  • 如果返回值小于 0,则表示 str1 小于 str2。
  • 如果返回值大于 0,则表示 str2 大于 str1。
  • 如果返回值 = 0,则表示 str1 等于 str2。

该函数的实现原理是通过比较ASCII码值来实现的。
在比较两个字符串大小后,则要交换两字符串,这里可以使用strcpy字符串复制函数来实现,它的原型如下:

char *strcpy(char *dest, const char *src)

功能就是将src中的内容复制到dest中。

3 实现

#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 / sizeof str1[0]), stdin);
    fgets(str2, (sizeof str2 / sizeof str2[0]), stdin);
    fgets(str3, (sizeof str3 / sizeof str3[0]), stdin);
    if (strcmp(str1, str2) > 0) {
		swap(str1,str2); // 比较str1和str2
	}
    if (strcmp(str2, str3) > 0) {
		swap(str2,str3); // 比较str2和str3
	}
    if (strcmp(str1, str2) > 0) {
		swap(str1,str2); // 比较str1和str2
	}
    printf("排序后的结果为:\n");
    printf("%s%s%s", str1, str2, str3);
    return 0;
}

void swap(char *s1, char *s2)
{
    char t[20];
    strcpy(t, s1);
    strcpy(s1, s2);
    strcpy(s2, t);
}

4 运行结果

请输入3个字符串,每个字符串以回车结束:
def
abc
bed
排序后的结果为:
abc
bed
def
发布了125 篇原创文章 · 获赞 199 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/syzdev/article/details/104390837
今日推荐