The std::string in C++ is a powerful class that simplifies string manipulation. Unlike char*, which is a raw pointer, std::string provides robust functionality such as memory management, built-in methods for operations like searching (find), copying, deleting, replacing, and inserting.
Key Features:
- Encapsulates many useful member functions.
- Manages the memory allocated for the internal character array.
2. String Constructor Variants
There are multiple ways to construct a std::string:
- An empty string:
std::string str; - From a C-style string:
std::string str("example"); - Copying another string:
std::string str_copy(str); - With repeated characters:
std::string str(5, 'x');
#include <iostream>
#include <string>
void demonstrateConstructors() {
std::string s1; // Default constructor
const char* cStr = "hello world";
std::string s2(cStr); // From C-string
std::cout << s2 << "\n";
std::string s3(s2); // Copy constructor
std::cout << s3 << "\n";
std::string s4(10, 'a'); // Repeated characters
std::cout << s4 << "\n";
}
3. Assignment Operations
Various assignment methods exist for modifying an existing string:
- From a C-style string.
- From another
std::string. - Using a single character.
- Assigning substrings or repeating characters.
void demonstrateAssignment() {
std::string str1 = "original";
std::string str2 = str1; // Copy assignment
std::cout << str2 << "\n";
std::string str3;
str3 = 'z'; // Single character assignment
std::cout << str3 << "\n";
str3.assign("new value"); // Assign from C-string
std::cout << str3 << "\n";
str3.assign("longer string", 7); // Partial assignment
std::cout << str3 << "\n";
str3.assign(5, 'x'); // Repeated characters
std::cout << str3 << "\n";
}
4. Concatenation
Concatenating strings can be done using operators or member functions:
- Using
+=with various types. - Appending parts of other strings.
void demonstrateConcatenation() {
std::string base = "base";
base += " additional"; // Using operator +=
std::cout << base << "\n";
base.append(" more data", 4); // Appending part of a C-string
std::cout << base << "\n";
std::string extra = "extra";
base += extra; // Concatenating two strings
std::cout << base << "\n";
}
5. Searching and Replacing
Searches locate specific patterns within a string:
- Find first or last occurrence.
- Replace substrings starting at specified positions.
void demonstrateSearchAndReplace() {
std::string sample = "abcdefabcdef";
// Find operations
size_t pos = sample.find("def");
std::cout << "Position: " << pos << "\n";
pos = sample.rfind("abc");
std::cout << "Reverse Position: " << pos << "\n";
// Replace operation
sample.replace(3, 3, "XXX");
std::cout << "After replace: " << sample << "\n";
}
6. Comparison
Strings can be compared lexicographically:
- Returns
0if equal. - Returns
1if greater. - Returns
-1if less.
void demonstrateComparison() {
std::string a = "apple";
std::string b = "banana";
int result = a.compare(b);
std::cout << "Comparison Result: " << result << "\n";
}
7. Character Access
Individual characters can be accessed via:
- Bracket notation:
[]. at()method with bounds checking.
void demonstrateCharacterAccess() {
std::string text = "sample";
// Accessing characters
std::cout << "First char: " << text[0] << "\n";
std::cout << "Last char: " << text.at(text.size() - 1) << "\n";
// Modifying characters
text[1] = 'X';
text.at(3) = 'Y';
std::cout << "Modified: " << text << "\n";
}
8. Insertion and Deletion
Insert and delete substrings at specific positions:
- Insertions add new content.
- Deletions remove existing content.
void demonstrateInsertDelete() {
std::string mutableStr = "insertdelete";
// Inserting
mutableStr.insert(6, "here ");
std::cout << "After insert: " << mutableStr << "\n";
// Deleting
mutableStr.erase(6, 5);
std::cout << "After erase: " << mutableStr << "\n";
}
9. Substrings
Extract portions of the string using substr:
void demonstrateSubstring() {
std::string fullText = "extract substring";
std::string sub = fullText.substr(8, 9);
std::cout << "Substring: " << sub << "\n";
}