21xrx.com
2024-03-29 22:44:37 Friday
登录
文章检索 我的文章 写文章
C程序按字母顺序对字符串进行排序
2021-07-07 09:10:53 深夜i     --     --
C

C程序按字母顺序对字符串进行排序:例如,如果用户输入字符串“programming”,则输出将是“aggimmnoprr”,因此输出字符串将包含按字母顺序排列的字符。 我们假设输入字符串只包含小写字母。 我们计算字符 'a' 到 'z' 在输入字符串中出现的次数,然后创建另一个字符串,其中包含字符 'a' 到 'z' 的次数与它们在输入字符串中出现的次数相同。

 

C程序

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


int main()
{
  char ch, input[100], output[100];
  int no[26] = {0}, n, c, t, x;

  printf("Enter some text\n");
  scanf("%s", input);

  n = strlen(input);

  /** Storing how many times characters (a to z)
    appears in input string in an array */

  for (c = 0; c < n; c++)
  {
    ch = input[c] - 'a';
    no[ch]++;
  }

  t = 0;

  /** Insert characters 'a' to 'z' in output string as many times
    as they appear in the input string */

  for (ch = 'a'; ch <= 'z'; ch++)
  {
    x = ch - 'a';

    for (c = 0; c < no[x]; c++)
    {
      output[t] = ch;
      t++;
    }
  }
  output[t] = '\0';

  printf("%s\n", output);

  return 0;
}


程序输出:

使用指针的 C 程序

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


void sort_string(char*);

int main()
{
   char string[100];

   printf("Enter some text\n");
   gets(string);

   sort_string(string);
   printf("%s\n", string);

   return 0;
}

void sort_string(char *s)
{
   int c, d = 0, length;
   char *pointer, *result, ch;

   length = strlen(s);

   result = (char*)malloc(length+1);

   pointer = s;

   for ( ch = 'a' ; ch <= 'z' ; ch++ )
   {
      for ( c = 0 ; c < length ; c++ )
      {
         if ( *pointer == ch )
         {
            *(result+d) = *pointer;
            d++;
         }
         pointer++;
      }
      pointer = s;
   }
   *(result+d) = '\0';

   strcpy(s, result);
   free(result);
}

下载排序字符串程序。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章