Tuesday, September 18, 2012

Code# 81:c program to sort a string in alphabetic order

| |
Basic C Language Program  to sort a string in alphabetic order  is explained below with a detailed explanation,you will find it easy to go through this program, Sample input and output screen shots has been provide for the better understandability to the user, leave a comment if you are satisfied with the code

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

void sort_string(char*);

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);
}

0 comments:

Post a Comment

Powered by Blogger.