Substring in C++

Substring in C++ is achieved using str::substr() which is a predefined function comes with string.h header file. This function basically takes two arguments pos and len. In this function the index starts from 0.

Basic Syntax

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

And the parameters are:

Parameter Description
pos The position from which the substring should start.
len Length of the substring that should will be returned. Means the last index of the string is pos+len
out [Optional] Alternate output array in which to place the result.

Return Value

This function will return string object which is a substring of given string.


Following are the examples for str::substr() method.

Example 1

#include <iostream>
#include <string.h>
using namespace std;

int main () {

// string declaration
string str="I love";

// substring str2
string str2 = str.substr (0,6);

size_t pos = str.find("love");

// substring str3
string str3 = str.substr (pos);

cout << "String str2 : " << str2 << "\nString str3 : " << str3;

return 0;

The output should be:

String str2 : I love
String str3 : love

Example 2

// CPP program for illustration of std::substr() method
#include <string.h>
#include <iostream>
using namespace std;

int main(){
    string temp = "Website=CrazyGeeks.ORG";

    // Get position of '=' using find()
    int pos = temp.find("=");
    // Get the substring
    string sub = temp.substr(pos + 1);

    // print original string
    cout << "String is: " << temp;

    // print substring
    cout << "\n\nSubstring is: " << sub;

    return 0;

The output should be:

String is: Website=CrazyGeeks.ORG

Substring is: CrazyGeeks.ORG