Q:

C program to sort a string in alphabetic order

0

C program to sort a string in alphabetic order

 

C program to sort a string in alphabetic order: For example, if a user inputs a string "programming," then the output will be "aggimmnoprr", so output string will contain characters in alphabetical order. We assume input string contains only lower case alphabets. We count how many times characters 'a' to 'z' appear in the input string and then create another string that contains characters 'a' to 'z' as many times as they appear in the input string

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

#include 
#include 
#include 
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;
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now