Monday, October 10, 2011

C++ example program to perform string related operations like string copy, string compare, string merge, upper and lower..



  In this example, various string operations like string copy, string compare, string merge, string uppercase, string lower case.
 
  Each operation is explained using separate function.

  Copy and paste the below code in a text file, and rename it as filename.cpp...

#include<iostream.h>
#include<ctype.h>
#include<string.h>
#include<conio.h>
class strhandle
{
 private:
  char str[100];
 public:
  strhandle();
  void get_str();
  void strcopy();
  void strmerge(char[]);
  void strcompare(char[],char[]);
  void struppercase();
  void strlowercase();
};
strhandle::strhandle()
{
 str[0]='\0';
}
void strhandle::get_str()
{
 cout<<"Enter the String to copy"<<endl;
 cin>>str;
}
void strhandle::strcopy()
{
 char *s1;
 strcpy(s1,str);
 cout<<"Copied string="<<s1<<endl;
}
void strhandle::strmerge(char *s2)
{
 cout<<"After merge:"<<strcat(str,s2)<<endl;
}
void strhandle::strcompare(char *s3, char *s4)
{
 int i;
 i=strcmp(s3,s4);
 if(i > 0)
 {
  cout<<"String "<<s3 << "is bigger than" << s4<<endl;
 }
 else if(i < 0)
 {
  cout<<"String "<<s3 << "is smaller than" << s4<<endl;
 }
 else
 {
  cout<<"Both string are equal"<<endl;
 }
}
void strhandle::struppercase()
{
 cout<<"Uppercase"<<endl;
 for(int i=0;i<strlen(str) ;i++)
 {
  cout<<(char)toupper(str[i]);
 }
 str[0]='\0';
 cout<<endl;
}
void main()
{
 clrscr();
 strhandle strobj;
 strobj.get_str();
 strobj.strcopy();
 char *str1;
 char *str2;
 char *str3;
 str1[0]='\0';
 str2[0]='\0';
 str3[0]='\0';
 cout<<"Enter the string to merge"<<endl;
 cin>>str2;
 strobj.strmerge(str2);
 str2[0]='\0';
 cout<<"Enter the first string to compare"<<endl;
 cin>>str2;
 cout<<"Enter the second string to compare"<<endl;
 cin>>str3;
 strobj.strcompare(str2,str3);
 str2[0]='\0';
 str3[0]='\0';
 strobj.struppercase();
 getch();
}

Hope this helps..
                                                                                                                                                                                  
                                                                                                                                    Techytips             

1 comments:

trustno1 said...

cplusplus programming codings
c++ code - tictactoe game

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

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