This post will discuss how to extract n characters from the end of a string in C++.

1. Using string::substr

We can use the string::substr function to extract a portion of a string. It takes the index of the first character to be extracted and the number of characters to be included in the substring. If the character count is not specified, all characters until the string’s end are included. The following C++ program demonstrates it:

Download  Run Code

2. Using std::copy

Another option is to copy the last n characters from the given string to a new string using the standard copy algorithm std::copy. It is included in the header <algorithm> and can be invoked as follows:

Download  Run Code

 
The <algorithm> header also offers the std::copy_n algorithm, which can be used to extract the last n characters in the following manner:

Download  Run Code

That’s all about extracting n characters from the end of a string in C++.