Strings
Strings
Resources [1] Object Oriented Programming with C++ (3rd Edition) E Balagurusamy [2] Teach Yourself C++ (3rd Edition) H Schildt
INTRODUCTION
A string is a sequence of character. We have used null terminated <char> arrays (C-strings or C-style strings) to store and manipulate strings. ANSI C++ provides a class called string. We must include <string> in our program.
AVAILABLE OPERATIONS
Creating string objects. Reading string objects from keyboard. Displaying string objects to the screen. Finding a substring from a string. Modifying string objects. Adding string objects. Accessing characters in a string. Obtaining the size of string. And many more.
String();
//
For creating a string object from a nullterminated string. For creating a string object from other string object.
string s1, s3; // Using constructor with no arguments. string s2(xyz); // Using one-argument constructor. s1 = s2; // Assigning string objects s3 = abc + s2; // Concatenating strings cin >> s1; cout << s2; getline(cin, s1) s3 += s1; s3 += abc;
// Reading from keyboard (one word)
// s3 = s3 + s1; // s3 = s3 + abc;
RELATIONAL OPERATIONS
Operator == != < <= > >= Equality Inequality Less than Less than or equal Greater than Greater than or equal Meaning
STRING CHARACTERISTICS
void display(string &str) { cout << Size = << str.size() << endl; cout << Length = << str.length() << endl; cout << Capacity = << str.capacity() << endl; cout << Max Size = << str.max_size() << endl; cout << Empty: << (str.empty() ? yes : no) << endl; cout << endl << endl; }
STRING CHARACTERISTICS
Function size() length() capacity() max_size() Task Number of elements currently stored Number of elements currently stored Total elements that can be stored Maximum size of a string object that a system can support Return true or 1 if the string is empty otherwise returns false or 0
emply()
resize()
find_last_of()
[] operator
For accessing individual character. Makes the string object to look like an array.
There is another overloaded version of compare int compare(int start_1, int length_1, string s_2, int start_2, int length_2) string s1, s2; int x = s1.compare(0, 2, s2, 2, 2); s1.swap(s2) Exchanges the content of string s1 and s2
LECTURE CONTENTS
15 (Full)
only Study the examples and exercise from both books carefully