天天看点

习题8-7 字符串排序

题目:

习题8-7 字符串排序 (20分)

题目要求:

本题要求编写程序,读入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()
{
	char s[5][100];
	char a[5][100];
	char tmp[100]; 
	char ch;
	int b[5]={ 0 }; //存每个字符串长度 
	int i = 0, j = 0;

	for( i = 0; i < 5; i++ )  //输入字符串  
    {  
        ch = getchar();  
        for( j = 0; ch != ' '; j++ )  
        {  
            s[i][j] = ch;  
            b[i]++;            //记录每一个字符串的长度  
            ch = getchar();  
            if( ch == '\n' )  
            {  
                break;  
            }  
        }  
    }  	

	for( i = 0; i < 5; i++ ) //保存每个字符串中的每个字符 
	{
		for( j = 0; j < 100; j++ )
		{
			if(  b[i] == j ) 
			{
				a[i][j] = '\0';	
				break;
			}
			a[i][j] = s[i][j];
		}
	}
	
	for( i = 0; i < 5; i++ ) //对各个字符串进行排序 
	{
		for( j = i + 1; j < 5; j++ ) 
		{ 
			if( strcmp( a[i], a[j] ) > 0 ) //字符串比较并交换 
			{
				strcpy( tmp, a[i] );
				strcpy( a[i], a[j] );
				strcpy( a[j], tmp );	
			}	
		} 
	}
	
	printf( "After sorted:\n" ); //结果输出 
	for( i = 0; i < 5; i++ )
	{
		printf( "%s\n", a[i] );
	}
	
	return 0;	
} 
           

继续阅读