C Program to Sort Strings in Alphabetical Order

Using this tutorial, We are going to talk about “C Program to Sort Strings in Alphabetical Order“. Let’s start the tutorial to clarify it clearly.

C Program to Sort Strings in Alphabetical Order

C Program to Sort Strings in Alphabetical Order

Program Code

#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 textn");
  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] = '';

  printf("%sn", output);

  return 0;
}

Final Words

We hope this article helps you to know about “C Program to Sort Strings in Alphabetical Order”. If you have any doubts about this topic then please let us know via the comment section. We will help you. Share this article with other C/C++ developers.

Share on:

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Comment