6 - A User-Defined String Class
6 - A User-Defined String Class
Lesson 6
Objectives
There are some features which are not available in C++ string class. Like
strDest = str Src; but we can obtain it by object oriented approach. Though the other
possible solution we will see later. So let we have our own ‘String’ class which is capable of
resolving said problem.
------------------------------------------------------------------------------------------------
#include <iostream> //String example , A Strings as a Class
#include <cstring>
using namespace std;
class String
{
private:
char str[80]; //name of widget part as string
public:
String ()
{str[0]=’\0’;}
String (char s[] )
{strcpy(str,s);}
Void display()
{cout<<str;}
Void concat(String s2)
{
If ( strlen(str) + strlen (s2.str) < 80)
Strcat(str,s2.str);
Else
Cout<<”\nString too long”;
}
};
Void main ( )
{
String s1(“Hello!”);
String s2 = ”How are you?”
String s3;
S3=s1;
AJ/Handout 6 -2- Object Oriented Programming
S3.concat(s2);
Cout<<”\n Concated S3= ”; s3.display();
}
Related Problems
Do strcpy, strcat by using other methods instead of using built-in function.
s3=s1;
cout<<”\nS3=”<<s3;
Void main()
{
AJ/Handout 6 -3- Object Oriented Programming
greeting +=nickname;
cout<<greeting<<endl;
The function getline() is same as get() with c-strings but not a member function. Instead its
first arguments is the stream object from which the input will come and second is the string
object where the text will placed.
Finding string Objects
The string class contains variety of member functions for finding srtings and substrings in
string object.
void main()
{
string s1=”In the name of Allah, the most beneficent the merciful.”;
int n;
n=s1.find(“Allah”);
cout <<”Found Allah at ::”<<n<<endl;
n=s1.find_first_not_of(“aeiouAEIOU”);
cout<<”First Consonant at: ”<<n<<endl;
}
Modifying string Objects
//changing part of string objects
#include<iostream>
#include<string>
using namespace std;
void main()
AJ/Handout 6 -4- Object Oriented Programming
{
string s1="A thing of beauty is a joy forever.";
string s2("Rose is a");
string s3("which ");
void main()
{
string aName=”Somro”;
string username;
if(username==aName)
cout<<”Greetings, Somro\n”;
else if (username<aName)
cout<<”You come before Somro\n”;
else if (username>aName)
cout<<”You come after Somro\n”;
int n= username.compare(0,2,aName,0,2)
cout<<”The first two letters of your name”;
if(n==0)
cout<<”match”;
else if(n<0)
cout<<”come before”;
else
cout<<”come after”;
cout<<aName.substr(0,2)<<endl;
}
Accessing character in string objects
//accessing characters in string objects
#include<iostream>
AJ/Handout 6 -5- Object Oriented Programming
#include<string>
using namespace std;
void main()
{
char charary[80];
string word;
cout<<"Enter a word:\n";
cin>>word;