This post will discuss how to extract the first few characters of a string in C++.

1. Using std::string::substr

The standard solution to extract the first n characters of a string is using the std::string::substr function. It takes the index of the first character and the number of characters to be extracted.

Download  Run Code

2. Using std::string::resize

Alternatively, we can use the std::string::resize function to resize a string to the specified length. To avoid modifications to the original string, invoke resize on a copy of the string, as shown below:

Download  Run Code

3. Using std::copy_n

We can also use the std::copy_n algorithm from header <algorithm> to extract the first n characters from a string. It can be used as follows to copy the first n characters:

Download  Run Code

That’s all about extracting the first few characters of a string in C++.