Search⌘ K
AI Features

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.

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.

C++ 17
#include <iostream>
#include <string>
int main() {
std::string s = "hello world";
// Extract the first five characters (indices 0 through 4)
// Start at index 0, take 5 characters.
std::cout << "Substring from index 0, length 5: \""
<< s.substr(0, 5) << "\"" << std::endl;
// Extract characters from index 6 to the end
// Start at index 6, take 5 characters.
std::cout << "Substring from index 6, length 5: \""
<< s.substr(6, 5) << "\"" << std::endl;
// Extract a shorter prefix (indices 0 through 2)
std::cout << "Substring from index 0, length 3: \""
<< s.substr(0, 3) << "\"" << std::endl;
return 0;
}

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.

C++ 17
#include <iostream>
#include <string>
int main() {
std::string s = "hello world";
// Extract from index 6 to the end
std::cout << "Substring from index 6 to the end: \""
<< s.substr(6) << "\"" << std::endl;
// Extract from index 0 to the end (entire string)
std::cout << "Full string via substr(0): \""
<< s.substr(0) << "\"" << std::endl;
return 0;
}

When the starting index is 0 and the length is omitted, the entire string is returned as a new copy. ...