The C++ std::string::substr() function is used to obtain the substring from a given string object. It takes two parameters: the starting position of the substring and the length of the substring. This function returns a new string object containing the specified portion of the original string.
If the length parameter is misplaced, It defaults to extracting the substring from the starting position to the end of the string.
SyntaxFollowing is the syntax for std::string::substr() function.
string substr (size_t pos = 0, size_t len = npos) const;Parameters
This function returns a string object.
Example 1Following is the basic program to create a substring starting at index 0 and ending with the index 10 using std::substr() function in C++.
#include <iostream> #include <string> using namespace std; int main() { string str = " Tutorialspoint "; string sub = str.substr(0, 10); cout << sub << endl; return 0; }Output
Let us compile and run the above program, this will produce the following result −
TutorialsExample 2
In this example, the substr is called only with the starting position, so it creates a substring from that position to the end of the string.
#include <iostream> #include <string> using namespace std; int main() { string str = " Tutorialspoint "; string sub = str.substr(10); cout << sub << endl; return 0; }Output
If we run the above code it will generate the following output.
pointExample 3
Following is an another example to create a substring position greater than the string length results an out_of_range exception.
#include <iostream> #include <string> using namespace std; int main() { string str = " Tutorialspoint "; try { string sub = str.substr(50); } catch (const std::out_of_range & e) { cout << "Exception: " << e.what() << endl; } return 0; }Output
Following is the output of the above code.
Exception: basic_string::substr: __pos (which is 50) > this->size() (which is 16)Example 4
In this example we call substring with a starting postion equal to the string's length, it returns an empty string.
#include <iostream> #include <string> using namespace std; int main() { string str = "Tutorialspoint"; string sub = str.substr(str.length()); cout << "Empty string = '" << sub << "'" << endl; return 0; }Output
Following is the output of the above code.
Empty string = ''
string.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4