You are on page 1of 32

Object Oriented Programming

using C++
Course Code: ES203
MODULE V-Strings
Ms. Garima Srivastava
Asstt. Professor
Dept Of CSE/IT ASET
AUUP Lucknow
Strings in C++
C++ provides following two types of string representations −
• The C-style character string.
• The string class type introduced with Standard C++.
The C-Style Character String
• The C-style character string originated within the C language and
continues to be supported within C++.
• This string is actually a one-dimensional array of characters
which is terminated by a null character '\0’.
• Thus a null-terminated string contains the characters that
comprise the string followed by a null.

2
• The following declaration and initialization create a string
consisting of the word "Hello".
• To hold the null character at the end of the array, the size
of the character array containing the string is one more
than the number of characters in the word "Hello."
• char greeting[]={‘H’,’e’,’l’,’l’,’o’,’\0’};
• If you follow the rule of array initialization, then you can
write the above statement as follows −
• char greeting[]={“Hello”};
3
int main () {
char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << "Greeting message: ";
cout << greeting << endl;
return 0;
}
OUTPUT:
Greeting Message: Hello
4
The String Class in C++
• Standard C++ library provides a string class type that
supports all the operations mentioned above, additionally
much more functionality.
• C++ supports a wide range of functions that manipulate
null-terminated strings −
1. strcpy(s1, s2);
copies string s2 into string s1.

5
2.strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3. strlen(s1);
Returns the length of string s1.
4. strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.
5. strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6. strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
6
#include <cstring> // concatenates str1 and str2
using namespace std; strcat( str1, str2);
int main () { cout << "strcat( str1, str2): " <<
char str1[10] = "Hello"; str1 << endl;
char str2[10] = "World"; // total length of str1 after
char str3[10]; concatenation
int len ; len = strlen(str1);
// copy str1 into str3 cout << "strlen(str1) : " << len
<< endl; return 0;
strcpy( str3, str1);
}
cout << "strcpy( str3, str1) : "
<< str3 << endl;
7
String Class
• Given that C++ already contains some support for strings
as null-terminated character arrays, it may at first seem
that the inclusion of the string class is an exception to
this rule.
• However, this is actually far from the truth. Here is why:
Null-terminated strings cannot be manipulated by any of
the standard C++ operators.
• Nor can they take part in normal C++ expressions.

8
For example:
char s1[80], s2[80], s3[80];
s1 = "Alpha"; // can't do
s2 = "Beta"; // can't do
s3 = s1 + s2; // error, not allowed
• in C++ it is not possible to use the assignment operator to
give a character array a new value (except during
initialization), nor is it possible to use the + operator to
concatenate two strings.
9
These operations must be written using library functions, as
shown here:
strcpy(s1, "Alpha");
strcpy(s2, "Beta");
strcpy(s3, s1);
strcat(s3, s2);
• Since null-terminated character arrays are not technically
data types in their own right, the C++ operators cannot be
applied to them.
10
• More than anything else, it is the inability to operate on null-
terminated strings using the standard C++ operators that has
driven the development of a standard string class.
• There are three reasons for the inclusion of the standard string
• class:
• consistency (a string now defines a data type),
• convenience (you may use the standard C++ operators), and
• safety (array boundaries will not be overrun).
• Keep in mind that there is no reason that you should abandon
normal, null-terminated strings altogether.

11
• They are still the most efficient way in which to implement
strings.
• However, when speed is not an overriding concern, using
the new string class gives you access to a safe and fully
integrated way to manage strings.

12
• To have access to the string class, you must include
<string> in your program.
• The string class is very large, with many constructors
and member functions.
• Also, many member functions have multiple overloaded
forms.
• we will examine several of its most commonly used
features.

13
Constructors of String class
• The prototypes for three of its most commonly used ones
are shown here:
• string( ); //creates empty string object
• string(const char *str);
• creates a string object from the null-terminated string
pointed to by str. This form provides a conversion from
null-terminated strings to string objects.
• string(const string &str);
• creates a string from another string.
14
Operators
• = Assignment
• + Concatenation
• += Concatenation assignment
• == Equality
• != Inequality
• < Less than
• <= Less than or equal
• > Greater than
15
• >= Greater than or equal
• [] Subscripting
• << Output
• >> Input

16
• int main()
• {
• string str1("Alpha");
• string str2("Beta");
• string str3("Omega");
• string str4;
• // assign a string
• str4 = str1;
• cout << str1 << "\n" << str3 << "\n"; 17
• // concatenate two strings
• str4 = str1 + str2;
• cout << str4 << "\n";
• // concatenate a string with a C-string
• str4 = str1 + " to " + str3;
• cout << str4 << "\n";
• // compare strings
• if(str3 > str1) cout << "str3 > str1\n";
• if(str3 == str1+str2)
• cout << "str3 == str1+str2\n";
18
• /* A string object can also be
• assigned a normal string. */
• str1 = "This is a null-terminated string.\n";
• cout << str1;
• // create a string object using another string object
• string str5(str1);
• cout << str5;
• // input a string
• cout << "Enter a string: ";
• cin >> str5; cout << str5;}
19
• This program produces the following output:
• Alpha
• Omega
• AlphaBeta
• Alpha to Omega
• str3 > str1
• This is a null-terminated string.
• This is a null-terminated string.
• Enter a string: STL
• STL 20
Some string Member Functions

• Length(): Length of a String


• string str = 'hello’;
• cout<<str.length();

• Output:
• 5

21
Comparing Two Strings
string str1 = 'computer';
string str2 = 'science';
if (str1.compare(str2) == 0)
cout << 'strings are equal'
else
cout << 'strings are not equal’;

Output:
Strings are not equal

22
Appending Two Strings
string str1 = 'computer';
string str2 = 'science';
string str3 = str1 + ‘ ' + str2;
cout << str3;
• OR
string str1 = 'computer';
string str2 = 'science’;
str1.append(‘ ‘ );
str1.append(str2);
cout << str1;
23
Insert ,erase and Replace
string str1("String handling C++ style.");
string str2("STL Power");
cout << "Initial strings:\n";
cout << "str1: " << str1 << endl;
cout << "str2: " << str2 << "\n\n";
cout << "Insert str2 into str1:\n";
str1.insert(6, str2);
cout << str1 << "\n\n";

24
• // demonstrate erase()
• cout << "Remove 9 characters from str1:\n";
• str1.erase(6, 9);
• cout << str1 <<"\n\n";
• // demonstrate replace
• cout << "Replace 8 characters in str1 with str2:\n";
• str1.replace(7, 8, str2);
• cout << str1 << endl
25
Initial strings:
str1: String handling C++ style.
str2: STL Power
Insert str2 into str1:
StringSTL Power handling C++ style.
Remove 9 characters from str1:
String handling C++ style.
Replace 8 characters in str1 with str2:
String STL Power C++ style.
26
Searching a String
• find(): str.find(searchstring);
• Beginning at start, find() searches the invoking string for the first occurrence
of the string contained in source. If found, find() returns the index at which the
match occurs within the invoking string. If no match is found, then npos is
returned.
• rfind(): str.rfind(sourcestring);
• is the opposite of find() . Beginning at start, it searches the invoking string in
the reverse direction for the first occurrence of the string contained in search
(i.e, it finds the last occurrence of search within the invoking string). If found,
rfind() returns the index at which the match occurs within the invoking string.
If no match is found,npos is returned.
• npos is a constant static member value used to indicate that no matches
were found in the string.
27
• int main()
• {
• int i;
• string s1 =
• "Quick of Mind, Strong of Body, Pure of Heart";
• string s2;
• i = s1.find("Quick");
• if(i!=string::npos) {
• cout << "Match found at " << i << endl;
• cout << "Remaining string is:\n";
• s2.assign(s1, i, s1.size());
• cout << s2;
• } 28
• cout << "\n\n";
• i = s1.find("Strong");
• if(i!=string::npos) {
• cout << "Match found at " << i << endl;
• cout << "Remaining string is:\n";
• s2.assign(s1, i, s1.size());
• cout << s2;
• }
• cout << "\n\n";
• i = s1.find("Pure");

29
• if(i!=string::npos) {
• cout << "Match found at " << i << endl;
• cout << "Remaining string is:\n";
• s2.assign(s1, i, s1.size());
• cout << s2;}
• // find list "of"
• i = s1.rfind("of");
• if(i!=string::npos) {
• cout << "Match found at " << i << endl;
• cout << "Remaining string is:\n";
• s2.assign(s1, i, s1.size());
• cout << s2;}return 0;}
30
• Output:
Match found at 0
Remaining string is:
Quick of Mind, Strong of Body, Pure of Heart
Match found at 15
Remaining string is:
Strong of Body, Pure of Heart
Match found at 31
Remaining string is:
Pure of Heart
Match found at 36
Remaining string is:
of Heart 31
• Str1=“king”
• Str2=“martin”
• Str3=“luther”
• 1. + to concatenate the strings
• 2. use the append function to concatenate
• Use comparison operator to compare two strings

32

You might also like