Loading lessons...
Standard C++ Classes & the string Class
Standard C++ Classes & the string Class
The C++ Standard Library is a large collection of ready-made classes and functions, all in namespace std. Using them saves writing (and debugging) our own versions of common things: text, input/output, complex numbers, containers. This lesson surveys the standard classes and then studies the most used one in detail: string, which replaces C-style character arrays.
1. Overview of the Standard C++ Library
| Group | Main classes / templates | Header |
|---|---|---|
| Strings | string, wstring (both from basic_string) | <string> |
| Stream I/O | ios, istream, ostream, iostream, ifstream, ofstream, fstream, istringstream, ostringstream | <iostream>, <fstream>, <sstream> |
| Containers (STL) | vector, list, deque, set, map, stack, queue, priority_queue | <vector>, <list>, ... |
| Algorithms (STL) | sort, find, count, reverse, copy, ... (function templates) | <algorithm> |
| Iterators, function objects | iterator, less, greater, plus | <iterator>, <functional> |
| Numerics | complex, valarray, accumulate | <complex>, <numeric> |
| Exceptions | exception, bad_alloc, out_of_range, runtime_error, ... | <exception>, <stdexcept> |
| Utilities | pair, auto_ptr (C++98), bitset, numeric_limits | <utility>, <memory>, <bitset>, <limits> |
| C library | strlen, sqrt, rand, ... | <cstring>, <cmath>, <cstdlib> |
The standard classes are ordinary C++ classes and class templates: they use constructors, destructors, operator overloading, templates and exceptions, exactly as in the earlier lessons.
Example: the complex class
complex<T> overloads the arithmetic operators and <<, so complex numbers can be used like built-in numbers.
#include <iostream>
#include <complex>
using namespace std;
int main() {
complex<double> a(3, 4), b(1, -2);
cout << "a = " << a << endl; // printed as (real,imag)
cout << "a + b = " << a + b << endl;
cout << "a * b = " << a * b << endl;
cout << "|a| = " << abs(a) << endl; // modulus
cout << "real(a) = " << a.real() << ", imag(a) = " << a.imag() << endl;
return 0;
}Output:
a = (3,4)
a + b = (4,2)
a * b = (11,-2)
|a| = 5
real(a) = 3, imag(a) = 42. Why the string Class?
C-style strings (char arrays ending in '\0') have several problems:
C-style string (char[]) | string class |
|---|---|
| fixed size chosen in advance; overflow is possible | grows and shrinks automatically |
copied with strcpy, joined with strcat, compared with strcmp | copied with =, joined with +, compared with ==, < |
| the programmer manages memory | the class manages its own memory (RAII) |
| no bounds checking | at() checks bounds and throws out_of_range |
length found by scanning (strlen) | length() is stored |
string is in header <string> and namespace std.
3. Creating string Objects
| Constructor | Example | Result |
|---|---|---|
| default | string s1; | empty string |
| from a C string | string s2("New York"); or string s2 = "New York"; | "New York" |
| copy | string s3(s2); | a copy of s2 |
| repeated character | string s4(5, '*'); | "*****" |
| part of another string | string s5(s2, 4, 4); | 4 characters from index 4: "York" |
4. Operators on Strings
| Operator | Meaning |
|---|---|
= | assignment |
+ | concatenation (string + string, string + C string, string + char) |
+= | append |
== != < <= > >= | comparison (dictionary order) |
[] | access a character (no bounds check) |
<< >> | output; input of one word (stops at whitespace) |
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1("Object"), s2 = "Oriented", s3;
s3 = s1 + " " + s2; // concatenation
s3 += " Programming"; // append
cout << "s3 = " << s3 << endl;
cout << "length = " << s3.length() << endl;
string a = "apple", b = "banana";
cout << "a < b ? " << (a < b) << endl; // dictionary order
cout << "a == \"apple\" ? " << (a == "apple") << endl;
s1[0] = 'o'; // characters can be changed
cout << "s1 = " << s1 << endl;
string stars(10, '*');
cout << stars << endl;
return 0;
}Output:
s3 = Object Oriented Programming
length = 27
a < b ? 1
a == "apple" ? 1
s1 = object
**********5. Important Member Functions
| Function | Task |
|---|---|
length(), size() | number of characters |
empty() | true if the string has no characters |
capacity(), max_size() | memory reserved now; the largest possible size |
at(i) | character at i, with bounds checking |
append(str) | add str at the end |
insert(pos, str) | insert str before position pos |
erase(pos, n) | remove n characters starting at pos |
replace(pos, n, str) | replace n characters from pos with str |
find(str) | position of the first occurrence of str, or string::npos if absent |
rfind(str) | position of the last occurrence |
find_first_of(chars) | position of the first character that is any of chars |
substr(pos, n) | a new string of n characters from pos |
compare(str) | 0 if equal, negative if less, positive if greater |
swap(other) | exchange contents with another string |
c_str() | a C-style const char* version (for old functions) |
getline(cin, s) | (a non-member) reads a whole line, including spaces |
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Guru Gobind Singh University";
cout << "find(\"Singh\") = " << s.find("Singh") << endl;
cout << "substr(5, 6) = " << s.substr(5, 6) << endl;
s.insert(28, " Delhi"); // insert at the end
cout << "after insert : " << s << endl;
s.replace(0, 4, "Shri Guru"); // replace "Guru"
cout << "after replace : " << s << endl;
s.erase(0, 5); // remove "Shri "
cout << "after erase : " << s << endl;
string::size_type pos = s.find("Mumbai");
if (pos == string::npos) {
cout << "\"Mumbai\" not found" << endl;
}
string x = "abc", y = "abd";
cout << "x.compare(y) = " << (x.compare(y) < 0 ? "negative" : "not negative") << endl;
x.swap(y);
cout << "after swap: x = " << x << ", y = " << y << endl;
cout << "first vowel at " << s.find_first_of("aeiou") << endl;
return 0;
}Output:
find("Singh") = 12
substr(5, 6) = Gobind
after insert : Guru Gobind Singh University Delhi
after replace : Shri Guru Gobind Singh University Delhi
after erase : Guru Gobind Singh University Delhi
"Mumbai" not found
x.compare(y) = negative
after swap: x = abd, y = abc
first vowel at 16. Characteristics: Size, Capacity and Bounds
#include <iostream>
#include <string>
#include <stdexcept>
using namespace std;
int main() {
string s;
cout << "empty? " << s.empty() << ", length " << s.length() << endl;
s = "C++";
s.reserve(50); // ask for room for 50 characters
cout << "length " << s.length() << ", capacity at least 50? " << (s.capacity() >= 50) << endl;
try {
cout << "s.at(1) = " << s.at(1) << endl;
cout << "s.at(9) = " << s.at(9) << endl; // out of range
} catch (out_of_range&) {
cout << "at(9) threw out_of_range" << endl;
}
return 0;
}Output:
empty? 1, length 0
length 3, capacity at least 50? 1
s.at(1) = +
at(9) threw out_of_range7. Reading Strings and Counting Words
cin >> s reads one word (it stops at a space). getline(cin, s) reads a whole line.
#include <iostream>
#include <string>
using namespace std;
int main() {
string line;
getline(cin, line); // the whole line, spaces included
int words = 0, vowels = 0;
bool inWord = false;
for (string::size_type i = 0; i < line.length(); i++) {
char c = line[i];
if (c != ' ' && !inWord) {
words++;
inWord = true;
}
if (c == ' ') {
inWord = false;
}
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowels++;
}
}
cout << "Line: " << line << endl;
cout << "Words: " << words << ", vowels: " << vowels << endl;
string reversed(line.rbegin(), line.rend()); // build from reverse iterators
cout << "Reversed: " << reversed << endl;
return 0;
}Input:
object oriented programming in c++Output:
Line: object oriented programming in c++
Words: 5, vowels: 10
Reversed: ++c ni gnimmargorp detneiro tcejbo8. Converting Between string and C Strings and Numbers
| Conversion | How (C++98) |
|---|---|
C string → string | string s = cstr; |
string → C string | s.c_str() |
number → string | an ostringstream: os << 42; s = os.str(); |
string → number | an istringstream: is >> n; or atoi(s.c_str()) |
(C++11 adds to_string and stoi.)
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
ostringstream out;
out << "Roll " << 42 << ", CGPA " << 8.75; // build a string like cout
string record = out.str();
cout << record << endl;
istringstream in("17 3.5 IPU");
int n;
double d;
string w;
in >> n >> d >> w; // parse a string like cin
cout << n * 2 << " " << d * 2 << " " << w << endl;
return 0;
}Output:
Roll 42, CGPA 8.75
34 7 IPUKey points to remember
- The standard library offers strings, streams, containers, algorithms,
complex, exceptions and utilities, all instd. stringmanages its own memory; use=,+,+=,==,<directly.- Key members:
length,at,append,insert,erase,replace,find(returnsstring::nposif absent),substr,compare,c_str. cin >> sreads a word;getline(cin, s)reads a line.at()checks bounds and throwsout_of_range;[]does not.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. What are the advantages of the
stringclass over C-style strings? Explain its important member functions with a program. (10 Marks) - Write: the comparison table, the constructors table, the member functions table, and the
Guru Gobind Singh Universityprogram with output. - Q2. Write a program to read a line and count its words and vowels using the
stringclass. (5 Marks) - Q3. Give an overview of the standard C++ library classes. (5 Marks)
- Write: the overview table and the
complexexample. - Q4. Differentiate between
cin >> sandgetline(cin, s). (2.5 Marks) - Q5. What does
find()return if the substring is not found? (2.5 Marks)