In C++, the <span><span>string</span></span> class is provided by the standard library (defined in the <span><span><string></span></span> header file) for convenient string (character array) manipulation. It encapsulates operations on character arrays, providing a rich set of member functions, thus avoiding the cumbersome and safety issues of manually managing character arrays in C (such as buffer overflows).
1. Basic Usage
1. Include the Header File
To use <span><span>std::string</span></span>, you need to include the header file:
#include <string>
using namespace std; // Optional, to avoid writing std:: each time
2. Definition and Initialization
string s1; // Empty string
string s2 = "hello"; // Initialized with C-style string
string s3("world"); // Constructor initialization
string s4(5, 'a'); // String composed of 5 'a's ("aaaaa")
string s5 = s2; // Copy initialization (s5 = "hello")
string s6(s2, 1, 3); // From index 1 of s2, take 3 characters ("ell")
2. Common Member Functions
1. String Length and Capacity
<span><span>length()</span></span>/<span><span>size()</span></span>: Returns the length of the string (number of characters).<span><span>empty()</span></span>: Checks if the string is empty (returns<span><span>true</span></span>when length is 0).<span><span>capacity()</span></span>: Returns the maximum number of characters the current string can hold without reallocating memory (greater than or equal to<span><span>size()</span></span>).<span><span>reserve(n)</span></span>: Pre-allocates memory to hold at least<span><span>n</span></span>characters, avoiding frequent expansions.<span><span>clear()</span></span>: Clears the string (length becomes 0, capacity remains unchanged).
string s = "hello";
cout << s.length() << endl; // Output: 5
cout << s.size() << endl; // Output: 5 (equivalent to length())
cout << s.empty() << endl; // Output: 0 (false)
s.clear();
cout << s.empty() << endl; // Output: 1 (true)
2. String Access
<span><span>operator[]</span></span>: Accesses the character at the specified index (no bounds checking, high efficiency).<span><span>at(index)</span></span>: Accesses the character at the specified index (with bounds checking, throws<span><span>out_of_range</span></span>exception on out of bounds).<span><span>front()</span></span>: Returns the first character (equivalent to<span><span>s[0]</span></span>).<span><span>back()</span></span>: Returns the last character (equivalent to<span><span>s[s.size()-1]</span></span>).
string s = "hello";
cout << s[1] << endl; // Output: 'e'
cout << s.at(2) << endl; // Output: 'l'
// s[10] // Undefined behavior (no check)
// s.at(10) // Throws exception (with check)
cout << s.front() << endl; // Output: 'h'
cout << s.back() << endl; // Output: 'o'
3. String Modification
<span><span>operator+=</span></span>/<span><span>append()</span></span>: Appends a string.<span><span>push_back(c)</span></span>: Adds a single character at the end.<span><span>insert(pos, str)</span></span>: Inserts the string<span><span>str</span></span>at the specified position<span><span>pos</span></span>.<span><span>erase(pos, n)</span></span>: Deletes<span><span>n</span></span>characters starting from position<span><span>pos</span></span>(if<span><span>n</span></span>is omitted, deletes to the end).<span><span>replace(pos, n, str)</span></span>: Replaces<span><span>n</span></span>characters starting from position<span><span>pos</span></span>with<span><span>str</span></span>.<span><span>swap(s)</span></span>: Swaps the contents with another string<span><span>s</span></span>(efficient, no memory copy).
string s = "hello";
s += " world"; // s becomes "hello world"
s.append("!"); // s becomes "hello world!"
s.push_back('?'); // s becomes "hello world!?"
s.insert(5, ","); // Inserts "," at index 5 → "hello, world!?"
s.erase(5, 2); // Deletes 2 characters from index 5 → "helloworld!?"
s.replace(5, 5, "java"); // Replaces 5 characters starting from index 5 with "java" → "hellojava!?"
string t = "cpp";
s.swap(t); // s becomes "cpp", t becomes "hellojava!?"
4. String Search
<span><span>find(str, pos)</span></span>: Searches for<span><span>str</span></span>starting from position<span><span>pos</span></span>, returning the index of the first occurrence; returns<span><span>string::npos</span></span>if not found. (string::npos is usually defined as -1)<span><span>rfind(str, pos)</span></span>: Searches for<span><span>str</span></span>in reverse starting from position<span><span>pos</span></span>, returning the index of the last occurrence.<span><span>find_first_of(str)</span></span>: Finds the index of the first occurrence of any character in<span><span>str</span></span><code><span><span>.</span></span><span><span>find_last_of(str)</span></span>: Finds the index of the last occurrence of any character in<span><span>str</span></span><code><span><span>.</span></span>
string s = "hello world, hello cpp";
size_t pos1 = s.find("hello"); // pos1 = 0
size_t pos2 = s.find("hello", 1); // Starts searching from index 1 → pos2 = 13
size_t pos3 = s.find("java"); // Not found → pos3 = string::npos
// string::npos is usually defined as -1
if (pos3 == string::npos) {
cout << "Not found" << endl;
}
size_t pos4 = s.rfind("hello"); // Reverse search for the last occurrence → pos4 = 13
5. String Substring
<span><span>substr(pos, n)</span></span>: Extracts<span><span>n</span></span>characters starting from position<span><span>pos</span></span>, returning a new string (if<span><span>n</span></span>is omitted, extracts to the end).
string s = "hello world";
string sub1 = s.substr(6, 5); // Takes 5 characters from index 6 → "world"
string sub2 = s.substr(6); // Takes from index 6 to the end → "world"
6. Other Common Functions
<span><span>c_str()</span></span>: Returns a pointer to a C-style character array of the string (<span><span>const char*</span></span>), used for compatibility with C functions (like<span><span>printf</span></span>).<span><span>data()</span></span>: Similar to<span><span>c_str()</span></span>, but since C++11, both are equivalent (returns<span><span>const char*</span></span>).<span><span>compare(str)</span></span>: Compares the current string with<span><span>str</span></span>, returning:
- 0: equal;
- positive: current string is greater;
- negative: current string is smaller.
3. Non-Member Functions (Helper Functions)
<span><span>operator+</span></span>: Concatenates two strings (like<span><span>s1 + s2</span></span>).<span><span>operator>></span></span>/<span><span>operator<<</span></span>: Input and output strings (like<span><span>cin >> s</span></span>,<span><span>cout << s</span></span>).<span><span>getline(cin, s)</span></span>: Reads a line of string (including spaces,<span><span>cin >> s</span></span><code><span><span> stops at spaces).</span></span><span><span>swap(s1, s2)</span></span>: Swaps two strings (same functionality as member function<span><span>swap</span></span>).
string s1 = "hello", s2 = "world";
cout << s1 + " " + s2 << endl; // Output: hello world
string s3;
getline(cin, s3); // Reads a line of input (like "hello world" fully read)
cout << s3 << endl;
4. Notes
<strong><span><span>string::npos</span></span></strong>: Is a static constant that indicates “not found” or “end”, usually the maximum value of<span><span>size_t</span></span>type.- Index starts from 0: Consistent with arrays, the first character index is 0.
- Memory Management:
<span><span>string</span></span>automatically manages memory, no need for manual release, avoiding memory leak issues of<span><span>char*</span></span><code><span><span> in C.</span></span> - Thread Safety: Multi-threaded read/write to the same
<span><span>string</span></span>object requires locking, otherwise it may lead to undefined behavior.
5. Application Scenarios
- Processing user input text (like usernames, passwords).
- String concatenation, splitting, replacing, and other text processing.
- Combined with file operations (reading/writing string content).
- Compatible with C-style strings (through
<span><span>c_str()</span></span>conversion).
<span><span>string</span></span> is the preferred tool for handling strings in C++, and its rich function interface greatly simplifies string operations while ensuring safety and efficiency.
