String Operations
Master advanced string operations including substring extraction, searching, replacing, and string manipulation techniques
Learn how to manipulate strings with powerful methods for searching, extracting, replacing, and transforming text data.
A Simple Example
#include <iostream>
#include <string>
int main() {
std::string email{"user@example.com"};
// Find position of '@'
size_t atPos{email.find('@')};
std::cout << "@ found at position: " << atPos << "\n"; // 4
// Extract username (before @)
std::string username{email.substr(0, atPos)};
std::cout << "Username: " << username << "\n"; // user
// Extract domain (after @)
std::string domain{email.substr(atPos + 1)};
std::cout << "Domain: " << domain << "\n"; // example.com
return 0;
}
Breaking It Down
find() - Search for Substring
- What it does: Searches for a substring and returns its position (index)
-
Returns: Position (size_t) if found,
std::string::nposif not found -
Syntax:
str.find(substring)orstr.find(substring, start_pos) -
Remember: Always check for
std::string::nposbefore using the position
substr() - Extract Substring
- What it does: Extracts a portion of the string
-
Syntax:
str.substr(start)extracts from start to end -
Syntax:
str.substr(start, length)extracts length characters - Remember: Position starts at 0, and length is the number of characters
replace() - Replace Substring
- What it does: Replaces part of the string with new content
-
Syntax:
str.replace(start, length, new_string) -
Example:
str.replace(0, 5, "Hello")replaces first 5 chars with "Hello" - Remember: It modifies the original string and returns a reference to it
insert() and erase() - Modify Strings
-
insert(pos, str): Inserts text at position pos -
erase(pos, length): Removes length characters starting at pos - Both modify the string in place
- Remember: Position indices shift after insert/erase operations
Why This Matters
- Real-world applications constantly need to manipulate strings: extracting usernames from emails, finding keywords in text, replacing placeholders in templates, parsing data formats.
- Mastering string operations is essential for text processing, data validation, parsing, and building user interfaces.
Critical Insight
The find() method returns std::string::npos when the substring isn't found. This is a special constant representing "not found" - always check for it before using the position! You can chain operations like find() and substr() to parse complex strings efficiently.
Think of string operations like text surgery: find() locates the problem, substr() extracts what you need, and replace() or erase() fixes it. Together, they let you parse, validate, and transform any text data.
Best Practices
Always check for npos: Before using a position returned by find(), check if it equals std::string::npos to ensure the substring was found.
Use size_t for positions: String positions and lengths should be stored in size_t, not int, to handle large strings correctly.
Chain operations carefully: When chaining find() and substr(), verify each step succeeds before proceeding to the next.
Consider rfind() for reverse search: Use rfind() to search from the end of the string, useful for finding file extensions or last occurrences.
Common Mistakes
Not checking for npos: Using find() result without checking leads to bugs when substring isn't found. Always verify the position is valid.
Off-by-one in substr: Remember substr(pos, len) uses length, not end position. substr(2, 3) gets 3 characters starting at position 2.
Infinite loop in replace all: When replacing all occurrences, update your search position after each replacement to avoid infinite loops.
Using returned position without adjustment: After find("age:"), add the length of the search term to move past it before extracting data.
Debug Challenge
This code tries to extract "cde" from "abcdefgh". Click the highlighted line to fix it:
Quick Quiz
- What does str.substr(2, 3) extract from "abcdefgh"?
- What is std::string::npos?
- What does str.replace(6, 5, "C++") do to "Hello World"?
Practice Playground
Time to try out what you just learned! Play with the example code below, experiment by making changes and running the code to deepen your understanding.
Output:
Error:
Lesson Progress
- Fix This Code
- Quick Quiz
- Practice Playground - run once