Basic String Operations
Explore basic string operations in C++ to understand substring extraction, concatenation, splitting, and joining techniques. Learn how each operation works, its time and space complexity, and best practices for efficient string manipulation using std::string methods and custom implementations.
We'll cover the following...
Now that we understand how strings are structured and accessed, the next step is to build familiarity with the fundamental operations available on std::string. These operations form the practical foundation of string algorithm implementation. Each one has a defined behavior and a measurable cost, and understanding both is essential before writing algorithms that depend on them.
Extracting a substring
A substring is a contiguous portion of a string. In C++, the substr() member function extracts a substring and returns it as a new std::string. The original string remains unchanged.
The substr() function takes two arguments: the starting index and the number of characters to extract.
In this example, s.substr(0, 5) extracts "hello", and s.substr(6, 5) extracts "world". The character at the starting index is included, and exactly the specified number of characters is taken.
Now, let’s look at the following visualizer for a better understanding of extracting substrings:
Omitting the length argument
If the length argument is omitted, substr() returns all characters from the starting index to the end of the string.
When the starting index is 0 and the length is omitted, the entire string is returned as a new copy. ...