输入以空格分开,并以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;
}
C语言动态字符串排序
最新推荐文章于 2021-05-20 14:40:03 发布