Extract first N characters in a string in C++
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <string> std::string findSubstr(std::string const &str, int n) { if (str.length() < n) { return str; } return str.substr(0, n); } int main() { std::string str = "C++20"; int n = 3; std::string substr = findSubstr(str, n); std::cout << substr << ' '; // C++ return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <string> std::string findSubstr(std::string str, int n) { // no-ref, no-const str.resize(n); return str; } int main() { std::string str = "C++20"; int n = 3; std::string substr = findSubstr(str, n); std::cout << substr << std::endl; // C++ return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <string> #include <algorithm> #include <iterator> std::string findSubstr(std::string const &str, int n) { std::string s; std::copy_n(str.begin(), n, std::back_inserter(s)); return s; } int main() { std::string str = "C++20"; int n = 3; std::string substr = findSubstr(str, n); std::cout << substr << std::endl; // C++ return 0; } |
That’s all about extracting the first few characters 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 :)