Working with the STL string Container in C++
String Container Overview
Basic Concepts
The string type in C++ represents a sequence of characters and is implemented as a class rather than a raw pointer like char*. It encapsulates a dynamic array of characters, offering built-in methods for manipulation.
Key characteristics:
- Encapsulates internal memory management
- Provides extensive member functions for operations like searching, copying, replacing, and inserting
- Safeguards against buffer overflows and invalid access through its internal mechanisms
Constructor Usage
The string class offers several constructors for initialization:
string(); // Default constructor
string(const char* s); // From C-style string
string(const string& s); // Copy constructor
string(size_t count, char c); // Repeat character
Example usage:
#include <iostream>
#include <string>
using namespace std;
void test_constructors() {
string empty_str; // Empty string
cout << "Empty: " << empty_str << endl;
const char* literal = "Hello";
string from_cstr(literal); // Initialize from C-string
cout << "From C-string: " << from_cstr << endl;
string copy_str(from_cstr); // Copy construction
cout << "Copy: " << copy_str << endl;
string repeated(5, 'A'); // Five A's
cout << "Repeated: " << repeated << endl;
}
Assignment Operations
Assigning values to strings can be done via overloaded operators or dedicated funcsions:
string& operator=(const char* s);
string& operator=(const string& s);
string& operator=(char c);
string& assign(const char* s);
string& assign(const char* s, size_t count);
string& assign(const string& s);
string& assign(size_t count, char c);
Example:
void test_assignment() {
string s1 = "Hello"; // Assignment from C-string
string s2 = s1; // Assignment from string
cout << "s1: " << s1 << " s2: " << s2 << endl;
string s3;
s3 = 'X'; // Assign single character
cout << "Single char: " << s3 << endl;
string s4;
s4.assign("World"); // Using assign function
cout << "Assigned: " << s4 << endl;
string s5;
s5.assign("World", 3); // Assign first 3 chars
cout << "Partial assign: " << s5 << endl;
string s6;
s6.assign(4, 'Y'); // 4 Y's
cout << "Repeated: " << s6 << endl;
}
Concatenation Methods
Strings can be joined using various approaches:
string& operator+=(const string& s);
string& operator+=(const char* s);
string& operator+=(char c);
string& append(const char* s);
string& append(const char* s, size_t count);
string& append(const string& s);
string& append(const string& s, size_t pos, size_t count);
Example:
void test_concatenation() {
string s1 = "Start";
s1 += "End"; // Append string
cout << "Concatenated: " << s1 << endl;
s1 += '!' ; // Append character
cout << "With exclamation: " << s1 << endl;
string s2 = "Middle";
s1 += s2; // Append another string
cout << "Final: " << s1 << endl;
s1.append(" Final"); // Using append method
cout << "Appended: " << s1 << endl;
}
Search and Replace
Finding and replacing substrings within a string:
int find(const string& str, size_t pos = 0);
int find(const char* s, size_t pos = 0);
int rfind(const string& str, size_t pos = string::npos);
string& replace(size_t pos, size_t count, const string& str);
Example:
void test_search_replace() {
string text = "abcdefgde";
int pos = text.find("de"); // Find first occurrence
if (pos != string::npos)
cout << "Found at position: " << pos << endl;
pos = text.rfind("de"); // Find last occurrence
cout << "Last found at: " << pos << endl;
string replaced = text;
replaced.replace(3, 3, "XYZ"); // Replace 3 chars starting at index 3
cout << "Replaced: " << replaced << endl;
}
String Comparison
Comparison is performed based on ASCII values:
int compare(const string& s) const;
int compare(const char* s) const;
Example:
void test_comparison() {
string a = "Apple";
string b = "Banana";
int result = a.compare(b);
if (result == 0)
cout << "Equal" << endl;
else if (result > 0)
cout << "Greater" << endl;
else
cout << "Less" << endl;
}
Character Access
Access individual characters using either operator[] or at():
char& operator[](size_t pos);
char& at(size_t pos);
Example:
void test_access() {
string str = "Hello";
cout << "Length: " << str.length() << endl;
for (size_t i = 0; i < str.length(); ++i)
cout << str[i] << " ";
cout << endl;
for (size_t i = 0; i < str.length(); ++i)
cout << str.at(i) << " ";
cout << endl;
str[0] = 'h'; // Modify first character
str.at(1) = 'E'; // Modify second character
cout << "Modified: " << str << endl;
}
Insertion and Deletion
Operations for modifying the string in-place:
string& insert(size_t pos, const string& s);
string& insert(size_t pos, size_t count, char c);
string& erase(size_t pos, size_t count = string::npos);
Example:
void test_insert_delete() {
string s = "Hello";
s.insert(1, "XX"); // Insert at index 1
cout << "After insert: " << s << endl;
s.erase(1, 2); // Delete 2 chars from index 1
cout << "After delete: " << s << endl;
}
Substring Extraction
Extract parts of a string using substr:
string substr(size_t pos = 0, size_t count = string::npos) const;
Example:
void test_substring() {
string email = "user@example.com";
size_t at_pos = email.find('@');
string username = email.substr(0, at_pos);
cout << "Username: " << username << endl;
}