Wednesday, May 18, 2016

c program to sort a given string alphabetically

Problem Statement:- you are given a string and you need to sort that string into their alphabetical order. Like in "enter" the first alphabet also comes first alphabetically so it will stay there and after that the secode 'e' must come.

#include<stdio.h>
#include<string.h>
#include<ctype.h>
void main()
{
 //random string as input
 char s[15]="enter";
 int i;
 char temp;
 printf("String entered is %s ",s);
//applying logic as bubble sort for string sorting
 for(i=0;i<strlen(s);i++)
  {
   for(int k=0;k<strlen(s)-i-1;k++)
    {
     //this  will use ASCII codes for characters
     if(s[k]>s[k+1])
     {
      temp=s[k];
      s[k]=s[k+1];
      s[k+1]=temp;
     }
    }
   }
 printf("\nString is %s",s);
}

output
String entered is  enter
String is eenrt

No comments:

Post a Comment