C语言动态字符串排序

输入以空格分开,并以enter结束
#include <stdio.h>
#include <stdlib.h>

void string_cpy(char *p, char *q)
{
	while(*q != '\0')
	{
		*p = *q;
		p++;
		q++;
	}
}

int string_cmp(char *p, char *q)
{
	while(*p != '\0' && *q != '\0')
	{
		if(*p > *q)
			return 1;
		else if(*p == *q)
		{
			p++;
			q++;
		}
		else if(*p < *q)
			return -1;
	}
	if(*p == '\0' && *q != '\0')
	{
		return -1;
	}
	else if(*p != '\0' && *q == '\0')
	{
		return 1;
	}
	else if(*p == '\0' && *q == '\0')
	{
		return 0;
	}
}

void paixu(char (*str)[32], int count)
{
	int i = 0;
	int n = 0;
	int j = 0;
	char tmp[32] = {0};
	int ret;

	while(i < count-1)				//字符串冒泡排序
	{
		while(n < count-1-i)
		{
			for(j = 0; j < 32; j++)
			{
				tmp[j] = '\0';
			}
			ret = string_cmp(str[n],str[n+1]);
			if(ret == 0)
				n++;
			else if(ret == -1)
				n++;
			else if(ret == 1)
			{
				string_cpy(tmp,str[n]);
				for(j = 0; j < 32; j++)			//中间数组先清空
				{
					str[n][j] = '\0';
				}
				string_cpy(str[n],str[n+1]);
				for(j = 0; j < 32; j++)
				{
					str[n+1][j] = '\0';
				}
				string_cpy(str[n+1],tmp);
				n++;
			}
		}
		i++;
		n = 0;
	}
}

int main(void)
{
	int i = 0;
	char *p;
	int count = 0,num;
	char str[256] = {0};
	char (*ptr)[32], (*s)[32];

	printf("please input some strings(enter to quit and separate with space):\n");
	gets(str);
	p = str;
	while(*p != '\0')
	{
		if(*p == ' ')
			count++;
		p++;
	}
	p = str;
	num = ++count;

	ptr = (char (*)[32])malloc(32 * (count+1));
	s = ptr;
	while(*p)	//非空执行	
	{
		count = 0;
		while(*p != '\0' && *p != ' ')
		{
			(*ptr)[count] = *p;		//申请二维数组空间后用二维数组的写法
			count++;
			p++;
		}
		if(*p == ' ')
		{
			p++;
			ptr++;
		}
	}
	ptr = s;

	printf("排序之前:");
	for(i = 0; i < num; i++)
	{
		printf("%10s",&ptr[i][0]);
	}
	puts(" ");
	paixu(ptr,num);
	printf("排序之后:");
	for(i = 0; i < num; i++)
	{
		printf("%10s",&ptr[i][0]);
	}
	puts(" ");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值