Wednesday, April 3, 2024

C program to sort a string in alphabetic order & Sorting of a Set of Strings in Ascending alphabetical order

 

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.

C program

#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 (= 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 (= 0; c < no[x]; c++)
    {
      output[t] = ch;
      t++;
    }
  }
  output[t] = '\0';

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

  return 0;
}

Output of program:
Sort a string program output


C Program – Sorting of a Set of Strings in Ascending alphabetical order

/* This program would sort the input strings in
 * an ascending order and would display the same
 */
#include<stdio.h>
#include<string.h>
int main(){
   int i,j,count;
   char str[25][25],temp[25];
   puts("How many strings u are going to enter?: ");
   scanf("%d",&count);

   puts("Enter Strings one by one: ");
   for(i=0;i<=count;i++)
      gets(str[i]);
   for(i=0;i<=count;i++)
      for(j=i+1;j<=count;j++){
         if(strcmp(str[i],str[j])>0){
            strcpy(temp,str[i]);
            strcpy(str[i],str[j]);
            strcpy(str[j],temp);
         }
      }
   printf("Order of Sorted Strings:");
   for(i=0;i<=count;i++)
      puts(str[i]);
   
   return 0;
}

Output:
sorted_strings_ascending

As you can observe in the above screenshot of output that we have entered 5 strings and the program then sorted them in ascending order. We got a sorted set of strings as output.

No comments:

Post a Comment

Matrix multiplication in C

  Matrix multiplication  in C: We can add, subtract, multiply and divide 2 matrices. To do so, we are taking input from the user for row num...