16

CHAPTER

Working with Strings

C
H
A
P
T
E
R

O
U
T
L
I
N
E
—•  16.1 Introduction
—•  16.2 Moving from C String to C++ String
—•  16.3 Declaring and Initializing String Objects
—•  16.4 Relational Operators
—•  16.5 Handling String Objects
—•  16.6 String Attributes
—•  16.7 Accessing Elements of Strings
—•  16.8 Comparing and Exchanging
—•  16.9 Miscellaneous Functions

16.1 INTRODUCTION

A string is nothing but a sequence of characters. String can contain small and capital letters, numbers and symbols. String is an array of character type. Each element of string occupies a byte in the memory. Every string is terminated by a null character. The last character of such a string is null (‘’) character and the compiler identifies the null character during execution of the program. In a few cases, the null character must be specified explicitly. The null character is represented by ‘’, which is the last character of a string. It's ASCII and Hex values are zero. The string is stored in the memory as follows:

char country[6] =”INDIA” ; ;  // Declaration of an array ‘country’.

Here, text “INDIA” is assigned to array country[6]. The text is enclosed within double quotation mark.

I N D I A ‘’
73 78 68 73 65 00

Each character occupies a single byte in memory as shown above. At the end of the string, null character is inserted by the compiler. The first row shows elements of string and the second row shows their corresponding ASCII values. The compiler takes care of storing the ASCII numbers of characters in the memory. In addition, the ASCII value of NULL character is also stored in the memory.

The programmer can use the string in program for storing and controlling text .The text comprises of words, sentences, names etc. The various operations with strings such as copying, comparing, concatenation, or replacing requires lot of effort in ‘C’ programming. These strings are called as C-style string. In C using function declared in string.h header file, string manipulation is done. Table 16.1 describes these functions.

Table 16.1 String library functions

Functions Description
strlen( ) Determines length of a string
strcpy( ) Copies a string from source to destination
strncpy( ) Copies characters of a string to another string up to the specified length
strcmp( ) Compares characters of two strings (Function discriminates between small & capital letters.)
stricmp( ) Compares two strings (Function doesn't discriminate between small & capital letters.
strncmp( ) Compares characters of two strings up to the specified length
strnicmp( ) Compares characters of two strings up to the specified length. Ignores case
strlwr( ) Converts uppercase characters of a string to lowercase
strupr( ) Converts lowercase characters of a string to uppercase
strdup( ) Duplicates a string
strchr( ) Determines first occurrence of a given character in a string
strrchr( ) Determines last occurrence of a given character in a string
strstr( ) Determines first occurrence of a given string in another string
strcat( ) Appends source string to destination string
strncat( ) Appends source string to destination string up to specified length
strrev( ) Reversing all characters of a string
strset( ) Set all characters of string with a given argument or symbol
strnset( ) Set specified numbers of characters of string with a given argument or symbol
strspn( ) Finds up to what length two strings are identical
strpbrk( ) Searches the first occurrence of the character in a given string and then it displays the string starting from that character

Following program explains use of above functions.

16.1 Write a program to declare string (character array) . Read string through the keyboard and count the length of the string using string library function.

# include <iostream.h>
# include <constream.h>
# include <string.h>

int main( )
{

  char name[15];
  clrscr( );
  cout<<"
 Enter your name : ";
  cin>>name;
  cout <<"
 Length of name is : "<<strlen(name);
  return 0;
}

OUTPUT
Enter your name : Suraj
Length of name is : 5

Explanation: In the above program, the string is declared using the statement char name[15]; using the library function strlen( ) total number of characters entered is displayed.

16.2 Write a program to display reverse of entered string.

# include <iostream.h>
# include <constream.h>
# include <string.h>

int main( )
{
     char name[15];
     clrscr( );
     cout<<"
Enter your name : ";
     cin>>name;
     cout <<"
 Reverse string is : "<<strrev(name);
     return 0;
}

OUTPUT
Enter your name : Akash
Reverse string is : hsakA

Explanation: In the above program, a character array name[] is declared. String is entered through the keyboard. The strrev( ) function displays reverse string.

16.3 Write a program to initialize a string using different formats.

# include <iostream.h>
# include <constream.h>
# include <string.h>

int main( )
{
clrscr( );

char text[]="Welcome"; // Using double quote
char text1[]={‘W’,’e’,’l’,’c’,’o’,’m’,’e’,’'}; // using single quote
cout<<"
 First string : "<<text;
cout <<"
 Second string : "<<text1;
return 0;
}

OUTPUT
First string : Welcome
Second string : Welcome

Explanation: In this program, two methods of initialization of arrays are used. Here, both declaration and initialization are done in the same statement.

char text[]=”Welcome”;

In this statement array text[] is declared and it is initialized with string “Welcome”. It is an easy way to initialize character array. It is not necessary to include null character. Here also, size of array is not mentioned. When declaration and initialization is done in the same statement, the compiler determines the size of the array. Hence, it is optional to mention the size of array in the subscript[] bracket.

char text1[]={‘W’,’e’,’l’,’c’,’o’,’m’,’e’,’'}; // using single quote

A character array (string) can also be initialized as shown in the above statement. However, in this method each character must be included in the single quotation mark and must be separated by comma. The string should be terminated by null character. Hence, the second method is difficult as compared to the first. Here the programmer has to specify the null character at the end of string.

16.2 MOVING FROM C STRING TO C++ STRING

In the last few examples we observed that a string is nothing but a sequence of characters and it is declared as character array. However, manipulation of string in the form of character array requires more effort. C uses library function defined in string.h to carry string manipulation.

To make the string manipulation easy the ANSI committee added a new class called string. It allows us to define objects of string type and they can be used as built in data type. The string class is considered as another container class and not a part of STL (Standard Template Library). The STL is described in the next chapter. The programmer should include the string header file.

Instead of declaring character array an object of string, class is defined. Using member function of string class, string operations such as copying, comparison, concatenation etc. are carried out more easily as compared to C library functions.

The string class is very vast. It also contains several constructors, member functions, and operators. These constructors, member functions, and operators help us to perform the various operations with strings.

16.3 DECLARING AND INITIALIZING STRING OBJECTS

In C, we declare strings as given below:

char text[10];

whereas in C++ string is declared as an object. The string object declaration and initialization can be done at once using constructor in the string class. The constructors of the string class are described in Table 16.2.

Table 16.2 String constructors

Constructors Meaning
String ( ); Produces an empty string
String (const char *text); Produces a string object from a null ended string
String (const string & text); Produces a string object from other string objects

We can declare and initialize string objects as follows:

  Declaration of string objects
string text; // Using constructor without argument
string text(“C++”); // Using constructor with one argument
text1=text2 // Assignment of two string objects
text = “c++”+ text1 // Concatenation of string objects
cin>> text // Reads string without space through the keyboard
getline(cin, text) // Reads string with blank spaces

Two string objects can be concatenated using overloaded + operator. The overloaded += operator appends one string to the end of another string. The operators << and >> are overloaded operators and can be used for input and output operations.

text1+=text is equivalent to text1=text1+text
text1+=”xyz” is equivalent to text1=text1+”xyz”
cin >> text // Reads string without spaces
cout <<text // Displays the contents on the screen
getline (cin,text) // Reads string with blank spaces

Here are some illustrations based on the above concepts.

16.4 Write a program to declare string objects. Perform assignment and concatenation operations with the string objects.

# include <iostream>
# include <string>

using namespace std;
int main( )
{
string text;             // Vacant string object
string text1(" C++");    // Constructor with one argument
string text2(" OOP");

cout <<"text1 : "<<text1 <<"
";
cout <<"text2 : "<<text2 <<"
";
text=text1;     // assignment operation
cout <<"text : "<<text<<"
";
text=text1+" " + text2;
cout <<"Now text : "<<text;
  return 0;
}

OUTPUT
text1 : C++
text2 : OOP
text : C++
Now text : C++ OOP

Explanation: In the above program, three string objects text, text1, and text2 are defined. The object is not initialized. The objects text1 and text2 are initialized with the strings “C++” and “OOP” respectively. The object text is initialized with the contents of object text1 using ‘=’ operator as per the statement text=text1. Again joining of object text1 and text2 is done and resulting string is assigned to the object text as per the statement text=text1+” " + text2.

Table 16.3 describes various member functions of string class.

Table 16.3 String manipulating functions

   Function Use
append( ) Adds one string at the end of another string
assign( ) Assigns a specified part of string
at( ) Access the characters located at given location
begin( ) Returns a reference to the beginning of a string
capacity( ) Calculates the total elements that can be stored
compare( ) Compares two strings
empty( ) Returns false if the string is not empty, otherwise true
end( ) Returns a reference to the termination of string
erase( ) Erases the specified character
find( ) Finds the given sub string in the source string
insert( ) Inserts a character at a given location
length( ) Calculates the total number of elements of string
max_size( ) Calculates the maximum possible size of string in a given system
replace( ) Substitutes specified characters with the given string
resize( ) Modifies the size of the string as specified
size( ) Provides the number of characters in the string
swap( ) Exchanges the given string with another string

The operators used with arithmetic or comparison operations can be used with string objects. Table 16.4 describes these operators.

Table 16.4 String manipulating operators

Operator Working
= Assignment
+ Joining two or more strings
+= Concatenation and assignment
= = Equality
! = Not equal to
< Less than
<= Less than or equal
> Greater than
>= Greater than or equal
[ ] Subscription (used with array)
<< Insertion operator
>> Extraction operator

16.4 RELATIONAL OPERATORS

Table 16.4 describes various relational operators. These operators can be used with string objects for assignment, comparison etc. The following program illustrates the use of relational operators with string objects.

16.5 Write a program to compare two strings using string objects and relational operators.

# include <iostream>
# include <string>
using namespace std;

int main( )
{
string s1("OOP");
string s2("OOP");
if (s1==s2)
cout <<"
 Both the strings are identical";
else
cout <<"
 Both the strings are different";
return 0;
}

OUTPUT
Both the strings are identical

Explanation: In the above program, two string objects s1 and s2 are declared. Both the string objects are initialized with the string “OOP”. The if statement checks whether the two strings are identical or different. Appropriate message will be displayed on comparison. Thus, in this program the two string objects contain the same string and hence, it displays the message “Both the strings are identical”.

16.6 Write a program to compare two strings using standard function compare( ).

# include <iostream>
# include <string>

using namespace std;
int main( )
{
  string s1("aaa");
  string s2("bbb");
  int d=s1.compare(s2);

if (d==0)
cout <<"
 Both the strings are identical";
else if (d>0)
cout <<"s1 is greater than s2";
else
cout <<"s2 is greater than s1";
return 0;
}

OUTPUT
s2 is greater than s1

Explanation: In the given program, two string objects s1 and s2 are declared and initialized with the strings “aaa” and “bbb”. Both the string objects are compared using compare( ) function. The return value of function compare( ) is stored in the integer variable d. The function compare( ) returns zero if the two strings are same, otherwise it returns positive value. Using if..else condition appropriate messages are displayed.

16.5 HANDLING STRING OBJECTS

The member functions insert( ), replace( ), erase( ) and append( ) are used to modify the string contents. The following program illustrates the use of these functions:

insert( )

This member function is used to insert specified strings into another string at a given location. It is used in the following form:

s1.insert(3,s2);

Here, s1 and s2 are string objects. The first argument is used as location number for calling string where the second string is to be inserted.

16.7 Write a program to insert one string into another string using insert( ) function.

# include <iostream>
# include <string>

using namespace std;
int main( )
{
string s1("abchijk");
string s2("defg");

cout <<"
 s1= "<<s1;
cout <<"
 s2= "<<s2;
cout <<"
 after insertion";

s1.insert(3,s2);
cout <<"
 s1= "<<s1;
cout <<"
 s2= "<<s2;

return 0;
}

OUTPUT
s1= abchijk
s2= defg
after insertion
s1= abcdefghijk
s2= defg

Explanation: In the above program, two string objects s1 and s2 are declared and initialized with strings “abchijk” and “defg”. The insert( ) function inserts the string “defg” in the string “abchijk” at location 3. Now, the resulting string is “abcdefghijk”. In the statement s1.insert (3,s2), the object s1 invokes the member function insert( ) and passes the argument 3 and s2 explicitly.

erase( )

The erase( ) member function is used to erase/ remove specified characters from specified location. It is used in the following form:

s1.erase (3,7);

Here s1 and s2 are string objects. The first argument is starting element number and second argument is last element number i.e., character elements from 3 to 7 are removed.

16.8 Write a program to remove specified characters from the string.

# include <iostream>
# include <string>
using namespace std;

int main( )
{
string s1("abc12345defg");
cout <<"
 s1= "<<s1;
cout <<"
 after erase ( )";
s1.erase(3,5);
cout <<"
 s1= "<<s1;
return 0;
}

OUTPUT
s1= abc12345defg
after erase ( )
s1= abcdefg

Explanation: In the above program, s1 is a string object declared and initialized with string “abc12345defg”. The object s1 invokes the member function insert( ) with two integers 3 and 5. 3 indicates starting element number and 5 indicates number of characters to be erased. The insert( ) function erases next five characters from 3rd character.

replace( )

This member function replaces given character in a string. It requires three arguments as per the following format:

s1.replace(2,5,s2);

Here s1 and s2 are string objects.

16.9 Write a program to replace a string with given strings.

# include <iostream>
# include <string>

using namespace std;

int main( )
{
string s1("abcdefg");
cout <<"
 s1= "<<s1;
cout <<"
 after replace( )";
s1.replace(1,3,"BCD");
cout <<"
 s1= "<<s1;
cout<<"
";
return 0;
}

OUTPUT
s1= abcdefg
after replace( )
s1= aBCDefg

Explanation: In the above program, s1 is a string object initialized with “abcdefg”. The object s1 invokes the member function replace( ) with three arguments. The first argument indicates the starting character element, the second argument indicates the location of last character, and the third argument is a string that is to be replaced.

append( )

The above function is used to add a string at the end of another string. It is used in the following format:

s1.append(s2);

Here s1 and s2 are two objects. The contents of s2 are appended in the string s1.

16.10 Write a program to append one string at the end of another string .Use append( ) function.

# include <iostream>
# include <string>

using namespace std;

int main( )
{
string s1("abcdefg");
string s2("hijklmn");

cout <<"
 s1= "<<s1;
cout <<"
 after append ( )";

s1.append(s2);

cout <<"
 s1= "<<s1;
cout<<"
";
return 0;
}

OUTPUT
s1= abcdefg
after append ( )
s1= abcdefghijklmn

Explanation: In the above program, two string objects s1 and s2 are declared and initialized with the strings “abcdefg” and “hijklmn”. The s1 object invokes the member function append( ) and s2 is passed as argument. The string s2 is added at the end of string s1.

16.6 STRING ATTRIBUTES

The various attributes of the string such as size, length, capacity etc. can be obtained using member functions. The size of the string indicates the total number of elements currently stored in the string. The capacity means the total number of elements that can be stored in string. The maximum size means the largest valid size of the string supported by the system.

size( )

The member function size( ) determines the size of the string object i.e., number of bytes occupied by the string object. It is used in the given format.

s1.size( )

Here s1 is a string object and size( ) is a member function.

16.11 Write a program to display the size of the string object before and after initialization.

# include <iostream>
# include <string>

using namespace std;
 int main( )
{
  string s1;
  cout <<"
size : "<<s1.size( );
  s1="hello";
  cout <<"
Now size : "<<s1.size( );
  return 0;
}

OUTPUT
size : 0
Now size : 5

Explanation: In the above program, s1 is a string object. In the first cout statement s1 invokes the member function size( ), which returns the size of the string object s1. The size( ) object returns the size zero because the object s1 is empty. The object s1 is initialized with the string “hello.” In the second cout statement again the object s1 invokes the member function size( ). This time the size( ) member function returns the size 5. Thus, the size( ) function determines the size of the string object.

length( )

The member function length ( ) determines the length of the string object i.e. number of characters present in the string. It is used in the following format:

s1.length ( )

Here s1 is a string object and length ( ) is a member function.

The member functions size ( ) and length ( ) provide the same result. Each character occupies one byte in the memory. The number of bytes and total number of elements present in the string are always same, hence both these functions provide the same result.

16.12 Write a program to calculate the length of the string. Use member function length( ).

# include <iostream>
# include <string>

using namespace std;

int main( )
{
string s1;

cout <<"
 Length : "<<s1.length( );
s1="hello";
cout <<"
 Now Length : "<<s1.length( );

return 0;
}

OUTPUT
Length : 0
Now Length : 5

Explanation: The above program is same as the previous one. Here, instead of size( ) function, length( ) member function is used. The length( ) member function displays the length of the string object before and after initialization.

capacity( )

The member function capacity( ) determines the capacity of the string object i.e. number of characters it can hold. It is used in the following format:

s1.capacity( )

Here s1 is a string object and capacity( ) is a member function.

16.13 Write a program to display the capacity of the string object. Use member function capacity( ).

# include <iostream>
# include <string>

using namespace std;
int main( )
{
string s1;

cout <<"
 Capacity : "<<s1.capacity( );
s1="hello";
cout <<"
 Capacity : "<<s1.capacity( );

s1="abcdefghijklmnopqrstuvwxyzabcdef";
cout <<"
 Capacity : "<<s1.capacity( );
return 0;
}

OUTPUT

Capacity : 0
Capacity : 31
Capacity : 63

Explanation: In the above program, s1 is declared as a string object. The member function capacity( ) returns the capacity of the string object to hold the character elements. The maximum size of string in this system is 4294967293 and is obtained by the member function max_size( ). In this program the capacity ( ) function returns 31. We get different values in different situations. If the string object is empty the function returns 0. In case the string object contains string less than 32 characters, it returns 31. In this program, the string is initialized with 32 characters. The capacity( ) function returns the value 63 i.e. 32 + 31.

max_size( )

The member function max_size( ) determines the maximum size of the string object i.e. number of characters it can hold. It is used in the following format:

s1.max_size( )

Here s1 is a string object and max_size( ) is a member function.

16.14 Write a program to display the maximum size of the string object.

# include <iostream>
# include <string>

using namespace std;

int main( )
{
string s1;
cout <<"
 Maximum size : "<<s1.max_size( );
return 0;
}

OUTPUT
Maximum size : 4294967293

Explanation: In the above program, s1 is declared as a string object. The max_size( ) function returns the maximum size of the string object i.e. 4294967293.

empty( )

The empty( ) function determines whether the string is empty or filled. If the string is empty, it returns 1, otherwise 0. It is used in the following format:

s1.empty( )

Here s1 is a string object and empty( ) is a member function.

16.15 Write a program to determine whether the string object is initialized or not. Use empty( ) member function.

# include <iostream>
# include <string>

using namespace std;
int main( )
{
string s1;

cout <<"
 Empty : "<<(s1.empty ( )? "True" :"False");
s1="abc";
cout <<"
 Empty: "<<(s1.empty( ) ? "True" :"False");
return 0;
}

OUTPUT
Empty : True
Empty : False

Explanation: In the above program, s1 is declared as a string object and it is not initialized. The member function empty( ) is called with conditional operator. It displays the message true(1) i.e. string is empty.

The string object s1 is initialized with string “abc” and again empty( ) function is invoked. This time it returns false( ) i.e. string is not empty.

16.7 ACCESSING ELEMENTS OF STRINGS

It is possible to access particular word or single character of string with the help of member functions of string class. The supporting functions are illustrated with suitable examples.

at( )

This function is used to access individual character. It requires one argument that indicates the element number. It is used in the given format.

s1.at(5);

Here s1 is a string object and 5 indicates 5th element that is to be accessed.

16.16 Write a program to display the string elements one by one. Use the member function at( ).

# include <iostream>
# include <string>

using namespace std;

int main( )
{
string s1("PROGRAMMING");

for (int j=0;j<s1.length( );j++)
cout<<s1.at(j);

return 0;
}

OUTPUT
PROGRAMMING

Explanation: In the above program, s1 is a string object initialized with the string “PROGRAMMING.” The for loop is used to represent successive character location. The at( ) function with one integer argument displays the characters. The variable j indicates the element number.

The statement cout<<s1.at(j) displays the character. We can also use the overloaded operator [ ] to display the string without the use of at( ) function. Thus, the statement would be cout<<s1. [j].

find( )

The find( ) member function finds the given sub-string in the main string. It is used in the following format:

s1.find(s2);

Here s1 and s2 are string objects. The find( ) function searches the sub-string s2 in the main string s1.

16.17 Write a program to find sub-string from the source string.

# include <iostream>
# include <string>

using namespace std;

int main( )
{
string s1("Bangalore is the capital of Karnataka");

int x=s1.find("capital");

cout<<"Capital is found at : "<<x;

return 0;
}

OUTPUT
Capital is found at : 17

Explanation: In the above program, s1 is a string object and it is initialized with the string. The find( ) member function finds the given string in the source string. Here, in this program the find( ) function searches the word “capital” in the string s1. The find( ) function returns element number of the previous element from where the sub-string starts.

substr( )

The member function substr( ) is used to find sub-string in the main string. It requires two-integer arguments. The first argument indicates the starting element of the string and the second argument indicates the last argument of the string. It is used in the following format:

s1.substr(s,e);

Here s1 is a string object. The variables s and e are integer variables that indicate the starting and ending element number of the sub-string.

16.18 Write a program to retrieve the sub-string from the main string.

# include <iostream>
# include <string>

using namespace std;
int main( )
{
string s1 ("C plus plus");

cout <<s1.substr(2,4);
cout<<"
";

return 0;
}

OUTPUT
Plus

Explanation: In the above program, s1 is declared as a string object. It is initialized with the string “C plus plus.” The member function substr( ) requires two integer arguments, that indicate the starting and ending element of the sub-string. The sub-string is displayed on the screen.

find_first_of( )

This member function is used to find the first occurrence of the given character(s). It is used in the following format:

s1.find_first_of (‘p’);

Here s1 is a string object and ‘p’ is a character whose first occurrence is to be found.

16.19 Write a program to find the first occurrence of the given character. Use member function find_first_of( ).

# include <iostream>
# include <string>

using namespace std;

int main( )
{
string s1 ("C plus plus");

cout <<s1.find_first_of(‘p’);
cout<<"
";
  return 0;
}

OUTPUT
2

Explanation: In the above program, s1 is declared as string object and it is initialized with the string “C plus plus”. The member function find_first_of( ) searches the character ‘p’ and when finds it, returns the element number of the previous character.

find_last_of( )

This member function is used to find the last occurrence of the given character(s). It is used in the format given next.

s1.find_last_of(‘p’);

Here s1 is a string object and ‘p’ is a character whose last occurrence is to be found.

16.20 Write a program to find the last occurrence of the given character. Use member function find_last_of( ).

# include <iostream>
# include <string>

using namespace std;

int main( )
{
string s1 ("C plus plus");
cout <<s1.find_last_of(‘p’);
cout<<"
";
    return 0;
}

OUTPUT
7

Explanation: In the above program, s1 is declared as string object and it is initialized with the string “C plus plus”. The member function find_last_of( ) searches the character ‘p’ and when its last occurrence is found, returns the element number of the previous character.

16.8 COMPARING AND EXCHANGING

The string class contains functions, which allows the programmer to compare and exchange the strings. The related functions are illustrated below with suitable examples:

compare( )

The member function compare( ) is used to compare two string or sub-strings. It returns 0 when the two strings are same, otherwise returns a non-zero value. It is used in the following formats:

s1.compare(s2);

Here s1 and s2 are two string objects.

s1.compare (0,4,s2,0,4);

Here s1 and s2 are two string objects. The integer number indicates the sub-string of both the strings that are to be compared.

16.21 Write a program to compare two strings. Use compare( ) function.

# include <iostream>
# include <string>

using namespace std;

int main( )
{
string s1 ("Take");
string s2 ("Taken");

int d=s1.compare(s2);
cout <<"
 d= "<<d;

d=s1.compare (0,4,s2,0,4);
cout <<"
 d= "<<d;
return 0;
}

OUTPUT
d= -1
d= 0

Explanation: In the above program, s1 and s2 are two string objects initialized with the strings “Take” and “Taken” respectively. The first compare( ) statement checks the two string objects. It returns –1 i.e. the strings are not identical. In the second compare( ) statement, element numbers of both the strings that are to be compared are sent. Thus, passing element number sub-strings can be compared. In the above program, 0 to 4 elements of both the strings are compared. The function compare( ) returns 0 i.e. the two sub-strings are identical.

swap( )

The swap( ) member function is used to exchange the contents of two string objects. It is used in the following format:

s1.swap(s2);

Here s1 and s2 are two string objects. The contents of s1 are assigned to s2 and vice versa.

16.22 Write a program to exchange the contents of two string objects. Use the member function swap( ).

# include <iostream>
# include <string>

using namespace std;

int main( )
{
string s1 ("Take");
string s2 ("Took");

cout <<"
 s1= "<<s1;
cout <<"
 s2= "<<s2;

cout <<"
 After swap ( ) ";

s1.swap(s2);
cout <<"
 s1= "<<s1;
cout <<"
 s2= "<<s2;
return 0;
}

OUTPUT
s1= Take
s2= Took
After swap ( )
s1= Took
s2= Take

Explanation: In the above program, string objects s1 and s2 are declared and initialized with “Take” and “Took”. The swap( ) function exchanges the contents of s1 and s2 i.e. contents of s1 is assigned to s2 and vice versa. The output of the program is given above.

16.9 MISCELLANEOUS FUNCTIONS

assign( )

This function is used to assign a string wholly/ partly to other string object. It is used in the following format:

s2.assign(s1)

Here s2 and s1 are two string objects. The contents of string s1 are assigned to s2.

s2.assign(s1,0,5);

In the above format, element from 0 to 5 are assigned to object s2.

16.23 Write a program to assign a sub-string from main string to another string object.

# include <iostream>
# include <string> using namespace std;
int main( )
{
  string s1("c plus plus");
  string s2;
  int x=0;
  s2.assign(s1,0,6);
  cout <<s2;
  return 0;
}

OUTPUT
C plus

Explanation: In the above program, s1 and s2 are two string objects. The object s1 is initialized with the string “c plus plus”. The object s2 invokes the assign( ) function with the integer argument 0,6, that indicates the sub-string. The sub-string is assigned to object s2 i.e. “C plus”.

begin( )

This member function returns the reference of the first character of the string. It is used in the following format:

x=s1.begin( );

Here x is a character pointer and s1 is a string object.

16.24 Write a program to find starting character of a given string.

# include <iostream>
# include <string>
using namespace std;
int main ( )
}
  string s1("C plus plus");
  char *x;
  x=s1.begin( );
  cout <<*x;
  return 0;
}

OUTPUT
C

Explanation: In the above program, s1 is a string object and it is initialized with string “C plus plus”. The x is a character pointer. The object s1 invokes the function begin( ) and returns the starting address of the string s1 to character pointer x. The contents of x printed are ‘C’ i.e. the first character of the string.

SUMMARY

(1) A string is nothing but a sequence of characters. They are declared as character arrays. Each element of string occupies a byte in the memory. Every string is terminated by a null character.

(2) To make the string manipulation easy the ANSI committee added a new class called string. It allows us to define objects of string type and they can be used as built-in data type. The string class is considered as another container class and not a part of STL (Standard Template Library).

(3) Two string objects can be concatenated using overloaded + operator. The overloaded += operator appends one string to the end of another string. The operators << and >> are overloaded operators and can be used for input and output operations.

(4) Table 16.4 describes various relational operators. These operators can be used with string objects for assignment, comparison etc.

(5) The member functions insert( ), replace( ), erase( ) and append( ) are used to modify the string contents.

(6) The various attributes of the strings such as size, length, capacity etc. can be obtained using member functions. The size of the string indicates the total number of elements currently stored in the string. The capacity means the total number of elements that can be stored in the string. The maximum size means the largest valid size of the string supported by the system.

(7) It is possible to access particular word or single character of string with the help of member functions of string class such as at( ), find( ), substr( ), find_first_of( ) and find_last_of( ).

(8) The string class contains functions which allows the programmer to compare and exchange the strings. These functions are swap( ) and compare( ).

EXERCISES

[A] Answer the following questions.

(1) What do you mean by string?

(2) What is the difference between “a” and ‘a’?

(3) What is a string object?

(4) What is the difference between string object and character pointer?

(5) List any five string functions with their uses. Explain their syntaxes.

[B] Answer the following by selecting the appropriate option.

(1) A and B are two string objects. A=”abc” and B=”xyz”. A=A+B will produce

(a) “abcxyz”

(b) “abc”

(c) “xyzabc”

(d) none of the above

(2) The statement string a(“abc”)

(a) initializes string object

(b) replaces the string

(c) appends the string

(d) none of the above

(3) A string is initialized using

(a) default constructor

(b) explicit constructor

(c) assignment operator

(d) both (a) and (c)

(4) We can access string characters using

(a) at( ) function

(b) subscript operator [ ]

(c) ( )operator

(d) none of the above

[C] Attempt the following programs.

(1) Write a program to read three strings “C,” “PLUS” and “PLUS.” Concatenate them in a single string.

(2) Write a program to create an array of string objects. Read at least 10 names. Display the names alphabetically.

(3) Write a program to read a string. Count the number of vowels and spaces in the string.

(4) Write a program to read a string. Add the same string in the reverse order to the end of the same string.

(5) Write a program to read a string. Remove all duplicate letters from the string.

(6) Write a program to read a string. Change the first letter of every word capital.

(7) Write a program to display the reverse string of the entered string.

(8) Write a program to exchange the contents of two string objects. Use the member function swap( ).

(9) Write a program to display the string elements one by one. Use the member function at( ).

(10) Write a program to determine whether the string object is initialized or not. Use empty( ) member function.

(11) Write a program to declare string objects. Perform assignment and concatenation with the string objects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.114.85