如何用C语言给字母排序?

如何用C语言给字母排序?,第1张

#include <stdio.h>

int main()

{ char c[6]= {'c', 'a', 't', 'd', 'o', 'g'},t

int i,j

for (i=0i<5i++)

  for (j=0j<5-ij++)

    if(c[j]>c[j+1])

    { t=c[j]

      c[j]=c[j+1]

      c[j+1]=t

    }

for (i=0i<6i++)

  printf("%c ", c[i])

printf("\n")

return 0

}

思路:不同大小写组合,用字母差求字母在26个字母中相对位置作比较。

1、temp改成char类型。

2、添加一个函数,求字母相对位置(对应我的函数getLesOrder)

下面代码供参考:

#include <stdio.h>

#include <string.h>

int getLesOrder(char les)//获取大或小字母在26个字母中顺序(第几个字母)

{

  if(les>='a' &&les<='z') return les-'a'+1

  if(les>='A' &&les<='Z') return les-'A'+1

  return -1

}

void fun(char *q)

{

  int i,j,n

  char temp

  n=strlen(q)

  printf("%d\n",n)

  for(i=0i<n-1i++)

      for(j=i+1j<nj++)

          if(getLesOrder(q[i])>getLesOrder(q[j]))

              temp=q[i],q[i]=q[j],q[j]=temp

}

int main()

{

  char p[]="eacDFB"

  printf("%s\n",p)

  fun(p)

  printf("%s\n",p)

  return 0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/8091862.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-13
下一篇 2023-04-13

发表评论

登录后才能评论

评论列表(0条)

保存