Monday, October 10, 2011

C++ example program to sort a string.

This program can be used to sort a string...


/* String sorting */

#include<iostream.h>
#include<string.h>
#include<process.h>
#include<conio.h>
#define NULL 0
class string
{
 private:
  char str[100][100];
 public:
  void getstring(int);
  void display(int);
  void sortstr(int);
};
void string::getstring(int n)
{
 char temp[100];
 for(int i=0;i<n;i++)
 {
  cout<<"Enter the String"<<endl;
  cin>>temp;
  strcpy(str[i],temp);
 }

}

void string::display(int n)
{
 for(int i=0;i<n;i++)
 {
  cout<<endl<<"String "<<i+1 << ":" << str[i];
 }

}
void string::sortstr(int n)
{
 char temp[100];
 for(int i=0;i<n;i++)
 {
  for(int j=i+1;j<n;j++)
  {
   if(strcmp(str[i],str[j]) > 0 )
   {
    strcpy(temp,str[i]);
    strcpy(str[i],str[j]);
    strcpy(str[j],temp);
   }
  }
 }
}
void main()
{
 string strobj;
 clrscr();
 int nstr;
 cout<<"How many String to work"<<endl;
 cin>>nstr;
 strobj.getstring(nstr);
 strobj.sortstr(nstr);
 strobj.display(nstr);

}

Hope this helps..

                                                                                                                                         Techytips

Reactions:

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Bluehost Coupons