The string Class
I. In-Class Exercises
Programming Exercises
- Caesar Cipher: L2071
- Find the Lexicographically Smallest String: L2072
- Super Large Integer Comparison: L2073
- Password Compliance Check: L2074
II. Knowledge Summary
✨ Core Concept of the string Class
The string class is a data type in C++ that comes with built-in operations for representing and manipulating strings. It is defined in the <cstring> header file and requires the std namespace. Compared to character arrays, the string class is more convenient to use — it does not require manual memory management and supports a rich set of built-in operations.
✨ Definition, Initialization, and Access of the string Class
The string class has multiple initialization methods and supports accessing individual characters by index:
1#include <iostream>
2#include <cstring>
3using namespace std;
4
5int main() {
6 string str1; // Initialize as empty
7 string str2 = ""; // Initialize as empty
8 string str3(); // Initialize as empty
9 string str4 = "hello"; // Initialize to: hello
10 string str5("world"); // Initialize to: world
11 string str6(5, 'a'); // Initialize to: aaaaa
12
13
14 cout << str4 << endl;
15 cout << str5[2] << endl;
16
17
18 return 0;
19}✨ Common string Operations
1. Getting String Length
Methods to get the number of characters stored in a string:
- The length function
- The size function
1#include <iostream>
2#include <cstring>
3using namespace std;
4
5int main() {
6 // Getting the length of a string
7 string str = "hello";
8 int length = str.length(); // Get the length of str
9 cout << length << endl; // Output: 5
10
11 int size = str.size(); // Get the length of str
12 cout << size << endl; // Output: 5
13
14 return 0;
15}2. Concatenating Strings
Method to concatenate strings: Use the + operator to join multiple strings together.
1#include <iostream>
2#include <cstring>
3using namespace std;
4
5int main() {
6 string str1 = "hello";
7 string str2 = "world";
8 string str3 = str1 + " " + str2; // Concatenate three strings
9 cout << str3 << endl; // Output: "hello world"
10
11 return 0;
12}3. Appending Strings
Methods to append one string to the end of another:
- The += operator
- The append function
1#include <iostream>
2#include <cstring>
3using namespace std;
4
5int main() {
6 string str;
7
8 str = "hello"; // Set str to: "hello"
9 str += " world"; // Append " world" to str
10 cout << str << endl; // Output: "hello world"
11
12 str = "hello"; // Set str to: "hello"
13 char chs[10] = " world"; // Create char array chs initialized to: " world"
14 str += chs; // Append " world" to str
15 cout << str << endl; // Output: "hello world"
16
17 return 0;
18}1#include <iostream>
2#include <cstring>
3using namespace std;
4
5int main() {
6 string str;
7
8 str = "hello"; // Set str to: "hello"
9 str.append(" world"); // Append " world" to str
10 cout << str << endl; // Output: "hello world"
11
12 str = "hello"; // Set str to: "hello"
13 char chs[10] = " world"; // Create char array chs initialized to: " world"
14 str.append(chs); // Append " world" to str
15 cout << str << endl; // Output: "hello world"
16
17 str = "hello"; // Set str to: "hello"
18 str.append(3, '!'); // Append 3 '!' characters to str
19 cout << str << endl; // Output: "hello!!!"
20
21 return 0;
22}4. Inserting a Substring
Method to insert characters at a position within a string: Use the insert function.
1#include <iostream>
2#include <cstring>
3using namespace std;
4
5int main() {
6 string str;
7
8 str = "helrld"; // Set str to: "helrld"
9 str.insert(3, "lo wo"); // Insert "lo wo" at index 3 of str
10 cout << str << endl; // Output: "hello world"
11
12 str = "helrld"; // Set str to: "helrld"
13 char chs[10] = "lo wo"; // Create char array chs initialized to: "lo wo"
14 str.insert(3, chs); // Insert "lo wo" at index 3 of str
15 cout << str << endl; // Output: "hello world"
16
17 str = "helloworld"; // Set str to: "helloworld"
18 str.insert(5, 3, '-'); // Insert 3 '-' characters at index 5 of str
19 cout << str << endl; // Output: "hello---world"
20
21 return 0;
22}5. Erasing a Substring
Method to delete a portion of characters from a string: Use the erase function.
1#include <iostream>
2#include <cstring>
3using namespace std;
4
5int main() {
6 string str;
7
8 str = "he123llo"; // Set str to: "he123llo"
9 str.erase(2, 3); // Erase 3 characters starting from index 2, i.e., erase "123"
10 cout << str << endl; // Output: "hello"
11
12 str = "hello123"; // Set str to: "hello123"
13 str.erase(5); // Erase all characters from index 5 onward, i.e., erase "123"
14 cout << str << endl; // Output: "hello"
15
16 return 0;
17}6. Getting a Substring
Method to get a substring from a string: Use the substr function.
1#include <iostream>
2#include <cstring>
3using namespace std;
4
5int main() {
6 string str;
7
8 str = "he123llo"; // Set str to: "he123llo"
9 string sub_str1 = str.substr(2, 3); // Get 3 characters starting from index 2, i.e., "123"
10 cout << sub_str1 << endl; // Output: "123"
11
12 str = "hello123"; // Set str to: "hello123"
13 string sub_str2 = str.substr(5); // Get all characters from index 5 onward, i.e., "123"
14 cout << sub_str2 << endl; // Output: "123"
15
16 return 0;
17}7. Finding Characters and Substrings
Methods to find a character or substring: Use the find and rfind functions. find searches from left to right for the first match, and rfind searches from right to left for the last match. If not found, they return string::npos.
1#include <iostream>
2#include <cstring>
3using namespace std;
4
5int main() {
6 string str = "hello"; // Initialize str to: "hello"
7 size_t pos; // Store the found position in pos
8
9 pos = str.find('l'); // Find the first character 'l' in str
10 if (pos == string::npos) {
11 cout << "not find" << endl;
12 } else {
13 cout << pos << endl; // Output: 2
14 }
15
16 pos = str.find("l"); // Find the first substring "l" in str
17 if (pos == string::npos) {
18 cout << "not find" << endl;
19 } else {
20 cout << pos << endl; // Output: 2
21 }
22
23 pos = str.find("l", 3); // Starting from index 3, find the first "l" in the remaining string
24 if (pos == string::npos) {
25 cout << "not find" << endl;
26 } else {
27 cout << pos << endl; // Output: 3
28 }
29
30 pos = str.find("123", 3); // Starting from index 3, find the first "123" in the remaining string
31 if (pos == string::npos) {
32 cout << "not find" << endl; // Output: not find
33 } else {
34 cout << pos << endl;
35 }
36
37 pos = str.rfind("l"); // Find the last "l" in str
38 if (pos == string::npos) {
39 cout << "not find" << endl;
40 } else {
41 cout << pos << endl; // Output: 3
42 }
43
44 return 0;
45}✨ Execution Example of the string Class
Problem: Shift each letter in a string forward by k positions (wrapping around from 'z' to 'a'). For example, when k=3, 'a' becomes 'd', and 'x' becomes 'a'.
string str = "xyz";
int k = 3;
for (int i = 0; i < str.length(); i++) {
str[i] = (str[i] - 'a' + k) % 26 + 'a';
}Step-by-step execution:
| Step | i | str[i] | str[i]-'a' | +k | %26 | +'a' | Result |
|---|---|---|---|---|---|---|---|
| 1 | 0 | 'x' | 23 | 26 | 0 | 'a' | 'a' |
| 2 | 1 | 'y' | 24 | 27 | 1 | 'b' | 'b' |
| 3 | 2 | 'z' | 25 | 28 | 2 | 'c' | 'c' |
Final result: "abc"
Key technique: First subtract 'a' to map the letter to the range 0-25, add the offset and take modulo 26 to achieve wrapping, then add 'a' back.
✨ Common Mistakes with the string Class
- Wrong header file: The header file for the string class is
<string>, not<cstring>.<cstring>is the header file for C-style string functions (strlen, strcpy, etc.). However, if you use<bits/stdc++.h>, both are included. - Pitfalls when mixing string and character arrays: Strings can be concatenated with
+, but character arrays cannot."hello" + "world"will not concatenate two string literals because they are of typechar*. At least one operand must be of type string:string("hello") + "world". - Incorrect check for find return value:
findreturnsstring::nposwhen not found, which is a very large unsigned integer. Do not useif (str.find("abc") >= 0)to check if found, because npos is also greater than 0. The correct way isif (str.find("abc") != string::npos). - Misunderstanding erase and substr parameters: The second parameter is the length, not the end position.
str.erase(2, 3)erases 3 characters starting from index 2, not from index 2 to index 3. - Out-of-bounds access when modifying strings: When accessing via index
str[i], i must not exceedstr.length()-1. Although string is safer than character arrays, out-of-bounds indexing is still undefined behavior.
III. Homework
Knowledge Quiz
- The string Class - Quiz## Programming Exercises