The substr()
function is defined in the string.h
header and is used for string slicing in C++. It can be used to extract a part of a string, i.e., get a substring.
A substring is a sequence of consecutive characters from a string. For example, “with Educative” is a substring of “Learn C++ with Educative”.
The function will return a substring from the character of the pos
index (inclusive) up to the character with the (pos
+len
- 1) index. The original string will not be changed.
string substr (size_t pos = 0, size_t len = npos) const;
pos
: The position of the character from which the substring will start.len
: The number of characters to include in the substring.A string object is returned.
len
is greater than the size of the string, then len
is taken to be equivalent to the size of the string.pos
is greater than the size of the string, then the out_of_range
exception is thrown. No change will be made to the string.#include <iostream>#include<string.h>using namespace std;int main() {string str = "This is a really long sentence with a lot of words.";string substrTest;// we can see if we start indexing from 1,// the first letter is skipped and the substring// starts from 'h' not 'T'substrTest = str.substr(1,4);cout << substrTest << endl;// this substring will be from 'T' which has index 0// to 's' which has index 3substrTest = str.substr(0,4);cout << substrTest << endl;// this will give the last word of the sentence as it is 5 letters// and 'w' has index str.size() - 6substrTest = str.substr(str.size() - 6, 5);cout << substrTest << endl;// this will give substring from 'l' which has index 17// till 'e' in 'sentence' which has index 29 (17+13-1)substrTest = str.substr(17, 13);cout << substrTest << endl;// here the len is obviously larger than the size// of the string, so all the characters after and// including index 8 are extractedsubstrTest = str.substr(8, 100);cout << substrTest << endl;// since pos == str.size(), empty sting is returnedsubstrTest = str.substr(str.size(), 4);cout << substrTest << endl;// this will throw an error as pos > str.size()substrTest = str.substr(str.size() + 1, 4);return 0;}