In C++, the most commonly used tool for handling strings is the string class. It is safer and easier to use than C-style character arrays (char[]), helping us avoid many memory management issues. This article will guide you from scratch through the basic operations and common methods of string, making it suitable for beginners just starting to learn C++.
1. What is the string Class?¶
In C, strings are typically represented by character arrays (e.g., char str[] = "hello";), requiring manual memory management and prone to errors. In contrast, C++’s string class is part of the standard library, encapsulating string operations to allow us to handle strings like regular variables without worrying about memory allocation or out-of-bounds issues.
To use string, you must first include the <string> header and note the namespace:
#include <string> // Must include the header file
using namespace std; // Or use std::string explicitly
2. Defining and Initializing a string¶
1. Direct Assignment¶
The simplest way is to assign values to string variables using the equals sign:
string s1 = "Hello"; // Directly assign a string literal
string s2 = s1; // Copy an existing string
2. Using Constructors¶
The string class provides multiple constructors to initialize from character arrays, repeated characters, etc.:
string s3("World"); // Construct from const char*
string s4(5, 'A'); // Construct a string with 5 'A's (result: "AAAAA")
string s5; // Empty string (length 0)
3. Basic String Operations¶
1. Getting the String Length¶
Use size() or length() to get the length (both have the same effect):
string s = "C++";
cout << "Length: " << s.size() << endl; // Output: 3
cout << "Length: " << s.length() << endl; // Output: 3
Note:
size()returns asize_ttype (unsigned integer), not a regular integer.
2. Accessing Individual Characters¶
Access characters using [] or at():
string s = "hello";
cout << s[0] << endl; // Output 'h' (direct access, no bounds checking)
cout << s.at(1) << endl; // Output 'e' (safe access, throws exception on out-of-bounds)
Danger Warning:
[]does not check if the index is valid; out-of-bounds access may crash the program!
3. String Concatenation¶
Concatenate strings using +, +=, or the append() method:
string a = "Hello";
string b = " World";
// Method 1: + (returns a new string)
string c = a + b; // c = "Hello World"
// Method 2: += (modifies the original string)
a += b; // a becomes "Hello World"
// Method 3: append()
a.append("!"); // a becomes "Hello World!"
4. Common Member Functions¶
1. Finding Substrings: find()¶
find() searches for the position of a substring; returns string::npos (a large value) if not found:
string s = "abcdefg";
size_t pos = s.find("cd"); // Search for "cd"
if (pos != string::npos) {
cout << "Substring found at position: " << pos << endl; // Output: 2 (0-based index)
} else {
cout << "Substring not found" << endl;
}
2. Replacing Substrings: replace()¶
Replace a substring starting at a specific position and with a given length:
string s = "I like apple";
s.replace(2, 4, "love"); // Replace 4 characters starting at position 2 ("like") with "love"
cout << s << endl; // Output: "I love apple"
3. Inserting Substrings: insert()¶
Insert a string at a specified position:
string s = "Hello";
s.insert(5, " World"); // Insert " World" at position 5
cout << s << endl; // Output: "Hello World"
4. Deleting Substrings: erase()¶
Delete a substring starting at a specified position with a given length:
string s = "Hello World";
s.erase(6, 5); // Delete 5 characters starting at position 6 ("World")
cout << s << endl; // Output: "Hello"
5. Comparing Strings: compare()¶
Compare two strings and return:
- 0: Equal
- Positive: Current string is larger
- Negative: Current string is smaller
string a = "apple";
string b = "banana";
cout << a.compare(b) << endl; // Output: -1 (a < b)
6. Clearing the String: clear()¶
Remove all characters, resulting in an empty string:
string s = "test";
s.clear();
cout << s.size() << endl; // Output: 0
5. Converting Between Strings and Character Arrays¶
1. Converting string to const char*¶
Use c_str() to get the C-style (read-only) representation of the string:
string s = "hello";
const char* cstr = s.c_str(); // Convert to const char*
cout << cstr << endl; // Output: hello
2. Converting const char* to string¶
Directly use the constructor or assignment:
const char* cstr = "world";
string s(cstr); // Construct a string from const char*
string s2 = cstr; // Assign a const char* to a string
6. Important Notes¶
-
Include the Header File: Always include
<string>before usingstring; otherwise, the compiler will throw an error. -
Avoid Mixing C-Style Strings: Do not use C functions like
strcpyorstrcatwithstring; usestring’s built-in methods instead. -
Trap with size_t:
size()returnssize_t(unsigned integer). Be cautious when comparing with negative numbers:
if (s.size() > 0) { ... } // Correct (size is never negative)
if (s.size() > -1) { ... } // Incorrect! -1 becomes a large value, always true
- Check for Empty Strings: Use
empty()instead ofsize() == 0for clarity:
if (s.empty()) { ... } // Execute when s is empty
7. Summary¶
The string class is a core tool for handling strings in C++. Mastering its basic operations and common methods will simplify string processing code. Key takeaways:
- Definition & Initialization: Multiple construction methods
- Basic Operations: Length, character access, concatenation
- Common Methods: Find (find), replace (replace), insert (insert), delete (erase)
Practice the sample code to quickly familiarize yourself with these operations!