18.2 Moving from C String to C++ String
18.3 Declaring and Initializing String Objects
A string is nothing but a sequence of characters. Strings can contain small and capital letters, numbers, and symbols. A string is to be treated as an array of characters with terminating . Each element of a string occupies a byte in the memory. Every string is terminated by a null character. The last character of such a string is a null (‘ ’) character, and the compiler identifies the null character during the execution of the program. The programmer need not take care of the null character. In a few cases, the null character is to be specified explicitly. The null character is represented by ‘ ,’ which is the last character of a string. The null ( ) character is a byte with all bits at logic zero. Hence, ASCII and Hex values are zero. The string is stored in the memory in the following manner:
char country[6] =“INDIA”;//Declaration and initialization of an array country with 6 characters
Here, text “INDIA” is assigned to an array country [6]. The text is enclosed within double quotation marks.
As shown above, each character occupies a single byte in the memory. At the end of the string, a null character is inserted by the compiler. The first row shows the elements of the string, and the second row shows their corresponding ASCII values. The complier takes care of storing the ASCII numbers of the characters in the memory. In addition, the ASCII value of the null character is also stored in the memory.
The programmer can use the string in a program for storing and controlling the text. The text comprises words, sentences, names, and so on. The various operations with strings such as copying, comparing, concatenation, or replacing require a lot of effort in ‘C’ programming. These strings are called a C-style string. In ‘C,’ the string functions are declared in the string.h header file. Thus, using this header file, string manipulation is done. C++ also supports c style functions. Table 18.1 describes these functions.
Table 18.1 String library functions
Functions | Description |
---|---|
strlen() | Determines the length of a string |
strcpy() | Copies a string from the source to the destination |
strncpy() | Copies the characters of a string to another string up to the specified length |
strcmp() | Compares the characters of two strings (Function discriminates between small & capital letters.) |
stricmp() | Compares two strings (Function does not discriminate between small & capital letters.) |
strncmp() | Compares the characters of two strings up to the specified length |
strnicmp() | Compares the characters of two strings up to the specified length. Ignores case. |
strlwr() | Converts uppercase characters of a string into lowercase |
strupr() | Converts lowercase characters of a string into uppercase |
strdup() | Duplicates a string |
strchr() | Determines the first occurrence of a given character in a string |
strrchr() | Determines the last occurrence of a given character in a string |
strstr() | Determines the first occurrence of a given string in another string |
strcat() | Appends the source string to the destination string |
strncat() | Appends the source string to the destination string up to a specified length |
strrev() | Reverses all the characters of a string |
strset() | Sets all the characters of a string with a given argument or symbol |
strnset() | Sets a specified number of characters of a string with a given argument or symbol |
strspn() | Finds up to what length two strings are identical |
strpbrk() | Searches for the first occurrence of a character in a given string and then, displays the string starting from that character |
The following program explains the use of the above functions:
18.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(), the total number of charcters entered is displayed.
18.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. The string is entered through the keyboard. The strrev() function displays a reverse string.
18.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, the array text[] is declared, and it is initialized with the string “Welcome.” It is an easy way to initialize the character array. It is not necessary to include the null character. Here also, the size of the array is not mentioned. When declaration and initialization are done in the same statement, the compiler determines the size of the array. Hence, it is optional to mention the size of the array in the subscript[] brackets.
char text1[]={‘W’,‘e’,‘l’,‘c’,‘o’,‘m’,‘e’,‘ ’}; // using single // quotes
A character array (string) can also be initialized as shown in the above statement. However, in this method, each character should be included in single quotation marks and should be separated by commas. The string should be terminated by the null character. Hence, the second method is difficult as compared with the first. Here, the programmer has to specify the null character at the end of the string.
In the last few examples, we have observed that a string is nothing but a sequence of characters, and it is declared as a character array. However, the manipulation of a string in the form of a character array requires more effort. C uses a library function defined in string.h to carry out string manipulation.
To make the string manipulation easy, the ANSI committee added a new class called a string. It allows us to define objects of the string type, and they can be used as a built-in data type. The string class is considered another container class and not a part of STL (standard template library). The programmer should include the string header file.
Instead of declaring a character array, an object of the string class is defined. Using the member function of the string class, string operations such as coping, comparison, and concatenation are carried out more easily as compared with 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 perform various operations with strings.
In C, we declared a string as follows:
char text[10];
where, as in C++, a string is declared as an object. The string object declaration and initialization can be done once by using a constructor of the string class. The constructors of the string class are described in Table 18.2.
Table 18.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 another string object |
We can declare and initialize string objects as follows:
Declaration of String Objects | |
---|---|
string text; |
// Using constructors without |
|
// arguments |
string text(“C++”); |
// Using constructors with one |
|
// argument |
text1=text2 |
// Assignment of two string objects |
text =“c++”+ text1 |
// Concatenation of string objects |
cin>> text |
// Reading string without spaces |
|
// through the keyboard |
getline (cin, text) |
// Reading 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:
18.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 objects are 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, the joining of objects text1 and text2 is done, and the resulting string is assigned to the object text as per the statement text = text1+” “ + text2.
The Table 18.3 describes various member functions of string class.
Table 18.3 String manipulating functions
FUNCTION | USE |
---|---|
append() |
Adds one string at the end of another string |
assign() |
Assigns a specified part of a string |
at() |
Accesses the characters at a 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, it is true |
end() |
Returns a reference to the termination of a 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 a string |
max_size() |
Calculates the maximum possible size of a string in a given system |
replace() |
Substitutes the specified characters with a 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 18.4 describes these operators.
Table 18.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 to |
> |
Greater than |
>= |
Greater than or equal to |
[] |
Subscription (used with array) |
<< |
Insertion operator |
>> |
Extraction operator |
Table 18.4 describes various relational operators. These operators can be used with string objects for assignment, comparison, and so on. The following program illustrates the use of relational operators with string objects:
18.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. An 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”.
18.6 Write a program to compare two strings.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1(“aaa”);
string s2(“bbb”);
if (s1>s2)
cout<<“ s1 is greater than s2”;
if (s1==s2)
cout<<“ Both the strings are identical”;
else
cout<<“s2 is greater than s1”;
return 0;
}
OUTPUT
s2 is greater than s1
Explanation: In the above program, two string objects s1 and s2 are declared and initialized with the strings “aaa” and “bbb”, respectively. The nested if..else statement checks the two strings and displays the appropriate massages.
18.7 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 above program, two string objects s1 and s2 are declared and initialized with the strings “aaa” and “bbb”, respectively. Both the string objects are compared using the compare() function. The return value of the function compare() is stored in the integer variable d. The function compare() returns zero if the two strings are similar; otherwise, a positive value is returned. Using the if..else conditions, appropriate messages are displayed.
The member functions insert(), replace(), erase(), and append() are used to modify the string contents. The following program illustrates the use of these functions:
This member function is used to insert a specified string into another string at a given location. It is used in the following form:
s1.insert(3,s2);
where s1 and s2 are string objects. The first argument is the location number in the calling string where the second string is to be inserted.
18.8 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 the 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 arguments 3 and s2 explicitly.
The erase() member function is used to erase/ remove specified characters from a specified location. It is used in the following form:
s1.erase (3,7);
where s1 and s2 are string objects. The first argument is the starting element number, and the second argument is the last element number, that is, the character elements from 3 to 7 are removed.
18.9 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 that is declared and initialized with the string “abc12345defg”. The object s1 invokes the member function insert() with two integers 3 and 5. The 3 indicates the starting element number, and 5 indicates the number of characters to be erased. The insert() function erases the next five characters from the 3rd character.
This member function replaces the given characters in a string. It requires three arguments as per the following format:
s1.replace (2,5,s2);
where s1 and s2 are string objects.
18.10 Write a program to replace the string with the given string.
#include<iostream>
#include<string>
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 the last character, and the third argument is a string that is to be replaced.
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);
where s1 and s2 are two objects. The contents of s2 are appended in the string s1.
18.11 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()”;
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 an argument. The string s2 is added at the end of the string s1.
The various attributes of a string such as size, length, and capacity 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 a string. The maximum size means the largest valid size of the string supported by the system.
The member function size() determines the size of the string object, that is, the number of bytes occupied by the string object. It is used in the following format:
s1.size()
where s1 is a string object, and size() is a member function.
18.12 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;
}
size : 0
Now size : 5
Explanation: In the above program, s1 is a string object. In the first cout statement, the 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.
The member function length() determines the length of the string object, that is, the number of characters present in the string. It is used in the following format:
s1.length()
where s1 is a string object, and length() is a member function.
The member function size() and length()exhibit a similar result. Each character occupies one byte in the memory. The number of bytes and the total number of elements present in the string are always same; hence, both these functions exhibit a similar result.
18.13 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 similar to the previous one. Here, instead of the size() function, the length() member function is used. The length() member function displays the length of the string object before and after initialization.
The member function capacity() determines the capacity of the string object, that is, the number of characters it can hold. It is used in the following format:
s1.capacity()
where s1 is a string object, and capacity() is a member function.
18.14 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 the string in this system is 4294967293 that is obtained by the member function max_size(). In this program, the capacity() function returns 31. We get different values in various situations. If the string object is empty, the function returns 0. In case the string object contains a 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, that is, 32 + 31.
The member function max_size() determines the maximum size of the string object, that is, the number of characters it can hold. It is used in the following format:
s1.max_size()
where s1 is a string object, and max_size() is a member function.
18.15 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, the s1 is declared as a string object. The max_size() function returns the maximum size of the string object, that is, 4294967293.
The empty() function determines whether the string is empty or filled. If the string is empty, it returns 1; otherwise, it returns 0. It is used in the following format:
s1.empty()
where s1 is a string object, and empty() is a member function.
18.16 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 a conditional operator. It displays the message true (1), that is, the string is empty.
The string object s1 is initialized with the string “abc” and again, the empty() function is invoked. This time, it returns false (0), that is, the string is not empty.
It is possible to access a particular word or a single character of a string with the help of a member function of the string class. The supporting functions are illustrated with suitable examples.
This function is used to access an individual character. It requires one argument that indicates the element number. It is used in the following format:
s1.at (5);
where s1 is a string object, and 5 indicates the 5th element that is to be accessed.
18.17 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 that is initialized with the string “PROGRAMMING.” The for loop is used to represent a successive character location. The at() function with a one-integer argument displays the characters. The variable j indicates the element number.
The statement cout<<s1.at (j); displays the characters. We can also use the overloaded operator[] to display the string without use of the at() function. Thus, the statement would be cout<<s1. [j].
The find() member function finds the given sub-string in the main string. It is used in the following format:
s1.find (s2);
where s1 and s2 are string objects. The find() function searches for the sub-string s2 in the main string s1.
18.18 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 that is initialized with the string. The find() member function finds the given string in the source string. In this program, the find() function searches for the word “capital” in the string s1. The find() function returns the element number of the previous element from where the sub-string starts.
The member function substr() is used to find the 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);
where s1 is a string object. The variables s and e are integer variables that indicate the starting and ending element numbers, respectively, of the sub-string.
18.19 Write a program to retrieve the substring from the main string.
#include<iostream>
#include<string>
using namespace std;
int main()
{
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, which indicate the starting and ending elements of the sub-string. The sub-string is displayed on the screen.
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’);
where s1 is a string object, and p is a character whose first occurrence is to be found.
18.20 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 a string object that is initialized with the string “C plus plus.” The member function find_first_of() searches for the character ‘p’ and when it finds it, it returns the element number of the previous character.
This member function is used to find the last occurrence of the given character(s). It is used in the following format:
s1.find_last_of (‘p’);
where s1 is a string object, and p is a character whose last occurrence is to be found.
18.21 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 a string object that is initialized with the string “C plus plus.” The member function find_last_of() searches for the character p and when its last occurrence is found, it returns the element number of the previous character.
The string class contains functions that enable the programmer to compare and exchange the strings. The related functions are illustrated below with suitable examples:
The member function compare() is used to compare two strings or sub-strings. It returns 0 when the two strings are similar; otherwise, it 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 string objects. The integer number indicates the sub-string of both the strings that should be compared.
18.22 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 that are initialized with the strings “Take” and “Taken”, respectively. The first compare() statement checks the two string objects. It returns –1; that is, the strings are not identical. In the second compare() statement, the element numbers of both the strings that should be compared are sent. Instead of comparing two strings wholly part of one string and whole string of other is compared and tested. In the above program, 0 to 4 elements of both the strings are compared. The function compare() returns 0; that is, the two sub-strings are identical.
The swap() member function is used to exchange the contents of two string objects. It is used in the following format:
s1.swap (s2);
where s1 and s2 are two string objects. The contents of s1 are assigned to s2 and vice versa.
18.23 Write a program to exchange the contents of two string objects. Use the member function swap().
#include<iostream>
#include<string>
using namespace std;
{
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”, respectively. The swap() function exchanges the contents of s1 and s2; that is, the contents of s1 are assigned to s2 and vice versa. The output of the program is as given above.
This function is used to assign a string wholly/ partly to another string object. It is used in the following format:
s2.assign (s1)
where s1 and s2 are two string objects. The contents of the string s1 are assigned to s2.
S2.assign (s1,0,5);
In the above format, elements from 0 to 5 are assigned to the object s2.
18.24 Write a program to assign a substring from main string to another string object.
#include<iostream>
#include<string>
using namespace std;
{
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, which indicates the sub-string. The sub-string is assigned to the object s2, that is, “C plus”.
This member function returns the reference of the first character of the string. It is used in the following format:
x = s1.begin();
where x is a character pointer, and s1 is a string object.
18.25 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 that 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 the character pointer x. The contents of x printed are ‘C’; that is, the first character of the string.
18.26 Write a program to count total number of vowels present in the given string.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1;
string s2(“aeiou”);
int i,j,c=0;
cout<<“ Enter a string:”;
getline(cin,s1);
int l=s1.length();
for (i=0;i<l;i++)
{
for (j=0;j<5;j++)
if ( s1.at(i)==s2.at(j)) c++;
}
cout<<“ Total vowels present are:”<<c;
return 0;
}
OUTPUT
Enter a string : c plus plus
Total vowels present are : 2
Explanation: In the above program, the string objects s1 and s2 are declared. The s2 is initialized with the string “aeiou”. The string entered through the keyboard is assigned to the string object s1. Using the nested for loop and the if condition, vowels are checked in the main string. If a vowel is found, the counter variable c is incremented. At last, the value of c gives us the total number of vowels present in the string. The function at()gives the character at a particular location.
18.27 Write a program to find the length of the string excluding spaces.
#include<iostream>
#include<string>
int main()
{
string s1;
cout<<“ Enter a string:”;
getline(cin,s1);
int v=s1.length(),s=0;
for (int m=0;m<v;m++)
{
if (s1.at(m)==‘ ’)
s++;
}
cout<<“ Length of the string excluding spaces:”<<v-s;
return 0;
}
OUTPUT
Enter a string : C PLUS PLUS
Length of the string excluding spaces : 9
Explanation: In the above program, s1 is a string object. The string entered through the keyboard is assigned to the object s1. The length of the string s1 is calculated using the length() function and stored in the variable v. The for loop executes from 0 to v. The if condition checks every character of the string to see whether it a blank space or not. If it is a blank space, the counter variable s is incremented. When the for loop terminates, the variable s contains the total number of blank spaces present in the string. The string length is calculated by subtracting the spaces from the original length, that is, l-s.
18.28 Write a program that will read a line of text. Replace all the blank spaces with an underscore ( _).
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1;
cout<<“ Enter a string:”;
getline(cin,s1);
int l=s1.length();
for (int m=0;m<l;m++)
if (s1.at(m)==‘ ’)
s1.at(m)=‘_’;
}
cout<<“ s1:”<<s1;
return 0;
}
OUTPUT
Enter a string : C PLUS PLUS
s1 : C_PLUS_PLUS
Explanation: The above program is similar to the previous one. Here, when a blank space is found, it is replaced with the sign “_” (underscore). The statement s1.at (m)=‘_’ performs this task.
18.29 Write a program to display the reverse string of the entered string.
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s1;
cout<<“ Enter a string:”;
getline(cin,s1);
int v=s1.length();
for (int m=v;m>=0;m--)
cout<<s1[m];
return 0;
}
OUTPUT
Enter a string : WORLD
DLROW
Explanation: In the above program, the length of the string object is stored in the variable v. The for loop executes from v to 0, that is, in descending order. The statement cout<<s1[m] displays the characters on the screen.
(A) Answer the following questions
(B) Answer the following by selecting the appropriate option
(C) Attempt the following programs