C++ Substring

You can extract a substring from a string using the .substr() method.

Syntax:


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

pos: The starting position of the substring (index from where to start).

len: it extracts the substring from pos to the end of the string.

Example:


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

int main() {

    string str = "Hello World";
    string sub_str = str.substr(1, 4);  // Start at index 1 and take 4 characters
    // get the character from the string
    cout << "SubString " << sub_str << "\n";

    return 0;
}

Output:

SubString ello

Extracting Substring from a Specific Index to the End

You can also extract a substring starting from a position to the end of the string by leaving the length parameter out.

Example:


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

int main() {

    string str = "Hello World";
    string sub_str = str.substr(1);  // Start at index 1 
    // get the character from the string
    cout << "SubString " << sub_str << "\n";

    return 0;
}

Output:

SubString ello World