[PTA]习题8-7 字符串排序

Posted Spring-_-Bear

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[PTA]习题8-7 字符串排序相关的知识,希望对你有一定的参考价值。

[PTA]习题8-7 字符串排序

本题要求编写程序,读入5个字符串,按由小到大的顺序输出。

输入格式:
输入为由空格分隔的5个非空字符串,每个字符串不包括空格、制表符、换行符等空白字符,长度小于80。

输出格式:
按照以下格式输出排序后的结果:

After sorted:
每行一个字符串
输入样例:
red yellow blue green white
输出样例:
After sorted:
blue
green
red
white
yellow

  • 提交结果:

  • 源码:
#include<stdio.h>
#include<string.h>
int main(void)

	char str[5][81];

	for (int i = 0; i < 5; i++)   // 5个字符串
	
		scanf("%s", &str[i]);
	

	for (int i = 0; i < 4; i++)   // 选用选择排序法对5个字符串进行排序,比较4次可出结果
	
		for (int j = i + 1; j < 5; j++)   // 从剩下的5-i个字符串中进行比较
		
			if (strcmp(str[i], str[j]) > 0)   // 如果当前字符串大于后续字符串,则交换它们的值
			
				char temp[81];
				strcpy(temp, str[i]);
				strcpy(str[i], str[j]);
				strcpy(str[j], temp);
			
		
	

	printf("After sorted:\\n");   // 输出排序后的字符串

	for (int i = 0; i < 5; i++)
	
		printf("%s\\n", str[i]);
	

	return 0;

以上是关于[PTA]习题8-7 字符串排序的主要内容,如果未能解决你的问题,请参考以下文章

习题8-7 字符串排序

[PTA]习题7-1 选择法排序

[PTA]习题9-5 通讯录排序

PTA习题解析——目录树

[PTA]习题8-6 删除字符

[PTA]习题8-6 删除字符