Extract n characters from the end of a string in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <iostream> #include <string> std::string extractLastNChars(std::string const &str, int n) { if (str.size() < n) { return str; } return str.substr(str.size() - n); } int main() { std::string str = "C++17"; int n = 2; std::cout << extractLastNChars(str, n) << std::endl; // 17 return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> #include <string> #include <algorithm> std::string extractLastNChars(std::string str, int n) { if (str.size() < n) { return str; } std::string s; std::copy(str.end() - n, str.end(), std::back_inserter(s)); return s; } int main() { std::string str = "C++17"; int n = 2; std::string substr = extractLastNChars(str, n); std::cout << substr << std::endl; // 17 return 0; } |
The <algorithm> header also offers the std::copy_n algorithm, which can be used to extract the last n characters in the following manner:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include <iostream> #include <string> #include <algorithm> #include <iterator> std::string extractLastNChars(std::string str, int n) { if (str.size() < n) { return str; } std::string s; std::copy_n(str.end() - n, n, std::back_inserter(s)); return s; } int main() { std::string str = "C++17"; int n = 2; std::string substr = extractLastNChars(str, n); std::cout << substr << std::endl; // 17 return 0; } |
That’s all about extracting n characters from the end of a string in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)