How to use std::string::substr() in C++

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.

Prototype

string substr (size_t pos = 0, size_t len = npos) const;

Parameters

  1. pos: The position of the character from which the substring will start.
  2. len: The number of characters to include in the substring.

Return value

A string object is returned.

Important points

  1. In C++, the index starts from 0, not 1.
  2. If len is greater than the size of the string, then len is taken to be equivalent to the size of the string.
  3. If 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.

Code

#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 3
substrTest = 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() - 6
substrTest = 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 extracted
substrTest = str.substr(8, 100);
cout << substrTest << endl;
// since pos == str.size(), empty sting is returned
substrTest = 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;
}

Free Resources