天天看点

2012_2华中科技大学机试真题

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

/*
int cmp(const void *a,const void *b)
{
	return strcmp((char *)a,(char *)b);
}
*/
int strcomp(char *s1,char *s2)
{
	int len1=strlen(s1);
	int len2=strlen(s2);
	int i=0;
	while(i<len1&&i<len2)
	{
		if(tolower(s1[i])>tolower(s2[i]))
			return 1;
		else if(tolower(s1[i])<tolower(s2[i]))
			return 0;
		else i++;
	}
	if(len1>len2) return 1;
	else return 0;
}
int main()
{
	char **str;
	char *t,e;
	int row=1,col=1;
	int isNum=-1,i,j,k;
	str=(char **)malloc(row*sizeof(char *));
	str[row-1]=(char *)malloc(col*sizeof(char));
	printf("请输入字符串,串间用空格隔开,最后以回车结束:\n");
	while((e=getchar())!='\n')
	{
		if(e==' ')
		{
			str[row-1][col-1]='\0';
			col=1;
			row++;
			str=(char **)realloc(str,row*sizeof(char *));
			str[row-1]=(char *)malloc(col*sizeof(char));
			isNum=-1;
		}
		else if((e>='a'&&e<='z')||(e>='A'&&e<='Z'))
		{
			if(isNum==-1) isNum=0;
			else if(isNum==1)
				printf("输入错误,程序退出\n");
			if(isNum==0)
			{
				str[row-1][col-1]=e;
				col++;
				str[row-1]=(char *)realloc(str[row-1],col*sizeof(char));
			}
		}
		else if(e>='0'&&e<='9')
		{
			if(isNum==-1) isNum=1;
			else if(isNum==0)
				printf("输入错误,程序退出\n");
			if(isNum==1)
			{
				str[row-1][col-1]=e;
				col++;
				str[row-1]=(char *)realloc(str[row-1],col*sizeof(char));
			}
		}
	}
	str[row-1][col-1]='\0';
	for(i=0;i<row;i++)
		printf("%s\n",str[i]);
	for(i=row-1;i>0;i--)
	{
		k=0;
		for(j=0;j<i;j++)
		{
			if(strcomp(str[j],str[j+1])>0)
			{
				t=str[j];
				str[j]=str[j+1];
				str[j+1]=t;
				k=1;
			}
		}
		if(k==0)
			break;
	}
	for(i=0;i<row;i++)
		printf("%s\n",str[i]);
	return 0;
}