String sorting in alphabetic order

In this guide we will learn about string sorting with some program to sort a string in alphabetic order. We will take a string as input from the user then we will sort it using our C program.

If a user gives a string like “competitive” then we will  sort it and print “ceeiimopttv”. We consider that the user will give all the lowercase character here although you can sort a string if it contains uppercase. Then program will be a little bit complex.

C program to sort a sting

// string sorting c program

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

int main(){
  char first_string[200], second_string[200], cha;
  int len, x, y, r, str[26] = {0};

  printf("Enter any lowercase string to sort it : \n");
  scanf("%s", first_string);

  len = strlen(first_string);

  for(r = 0; r < len; r++){
    cha = first_string[r] - 'a';
    str[cha]++;
  }

  x = 0;

  for(cha = 'a'; cha <= 'z'; cha++){
    y = cha - 'a';

    for(r = 0; r < str[y]; r++){
      second_string[x] = cha;
      x++;
    }
  }

  second_string[x] = '\0';

  printf("\nSorted string is given bellow : \n%s\n", second_string);

  return 0;
}

Output of this string sorting program

string-sorting-c-program-c-program-to-sort-string

String sorting program using pointer in C

// string sorting using pointer in c

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

void str_sorting_func(char *str);

int main(){
   char main_string[200];

   printf("Enter a string to sort it here : \n");
   gets(main_string);

   str_sorting_func(main_string);
   printf("\nYour given string after sorting is : \n%s\n", main_string);

   return 0;
}

void str_sorting_func(char *str){
   int a, len, b = 0;
   char cha, *pt, *result;

   len = strlen(str);

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

   pt = str;

   for(cha = 'a' ; cha <= 'z' ; cha++ ){
      for(a = 0 ; a < len ; a++ ){
         if(*pt == cha){
            *(result + b) = *pt;
            b++;
         }
         pt++;
      }
      pt = str;
   }
   *(result + b) = '\0';

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

Output of sort string program

Enter a string to sort it here :
programming

Your given string after sorting is :
aggimmnoprr

Previous pageDelete vowels

Next pageRemove spaces