字符排序

规则1:英文字母从AZ排列,不区分大小写

规则2:同一个英文字母的大小写同时存在时,按照输入顺序排列

规则3:非英文字母的其它字符保持原来的位置

代码如下:

#include<stdio.h>
#include<malloc.h>

int sort_string(char* str)
{
 char *cpy;
 char temp;
 int pos[100];
 int i,j,same,flag,k,p;
 int len;
 int pos1,pos2;
 if(str == NULL)
  return -1;
    i=same=flag=0;
 do
 {
  i++;
 }while((*(str+i))!='\0');
 len=i;
 /*新建一个cpy数组,完全拷贝源字符串,以备相同字符查看先后顺序*/
 cpy=(char *)malloc(len+1);
 for(i=0;i<len;i++)
 {
  *(cpy+i)=*(str+i);
 }

 for(i=0;i<len;i++)
 {

/*判断是否属于英文字母*/
  if(!(('a'<=*(str+i)<='z') && ('A'<=*(str+i)<='Z')))
  {
   flag=1;
   goto nonletter;
  }
  for(j=i+1;j<len;j++)
  {
   if(!(('a'<=*(str+j)<='z') && ('A'<=*(str+j)<='Z')) || flag == 1)
    break;

/*判断是否是大小写字母,大小写字母ASCII码相差32*/
   if((*(str+i))-(*(str+j))==32 || (*(str+i))-(*(str+j))==-32)
   {
    same=1;
   }
   else
   {
    same=0;
   }

/*如果不是大小写字母则进行排序*/
   if((*(str+i)>*(str+j)) && same==0 )
   {

    temp=*(str+i);
    *(str+i)=*(str+j);
    *(str+j)=temp;
   }
  }
nonletter:
  continue;
 }
 for(i=0;i<len;i++)
 {
  for(j=i+1;j<len;j++)
  {

/*同一字母,但是有大小写区分,因此需要用输入的先后顺序来判断*/
   if((*(str+i))-(*(str+j))==32 || (*(str+i))-(*(str+j))==-32)
   {
    for(k=0;k<len;k++)
    {

/*查找字符在源串中的位置*/
     if(*(cpy+k)==*(str+i))
     {
      pos1=k;
     }
     else if(*(cpy+k)==*(str+j))
     {
      pos2=k;
     }
    }
    if(pos1>pos2)
    {
     temp=*(str+i);
     *(str+i)=*(str+j);
     *(str+j)=temp;
    }
   }
  }
 }
 free(cpy);
 return 0;
}

测试了一下,源串输入A Famous Saying: Much Ado About Nothing,预计输出A aaAAbc dFgghh: iimM nNn oooos Sttuuuy。验证了一下功能OK。但是代码的执行时间上可以在优化

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿与代码

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值