C++ string substr() Function
Example
Get two parts of a string:
string txt = "Hello World!";
cout << txt.substr(0, 5) << "\n";
cout << txt.substr(6);
Definition and Usage
The substr() function returns a new string with a part of the original string. The original string is not changed.
If you do not give a length, the new string has all the characters from the start position to the end.
The substr function is defined in the <string> header file.
Note: If the start position is larger than the length of the string, substr() throws an out_of_range exception (an error).
Syntax
string.substr(size_t start, size_t length);
The size_t data type is a non-negative integer.
Parameter Values
| Parameter | Description |
|---|---|
| start | Optional. The position of the first character. Default is 0. |
| length | Optional. The number of characters. Default is all characters to the end of the string. |
Technical Details
| Returns: | A new string with the selected characters. |
|---|
Related Pages
Read more about strings in our String Tutorial.