C++ / learning / What to remember · October 21, 2021 0

C++ substr()

In C++, the substr() method is one of the easiest functions to use to split a string into multiple slices. Here are the parameters of the substr():

name.substr(position, len)

where name is the string that you want to be sliced, position is the staring point, and len is the number of characters to include starting from pos.

Example:


#include <iostream>
using namespace std;
int main()
{
    string command;
    cin >> command;
    string sliced = command.substr(0, 5);
    cout << "first 5 letters of " << command << " is: " << sliced << endl;
}

Example output:

>>> Hello! How are you?
<<< first 5 letters of Hello! How are you? is: Hello

Note: >>> means input, and <<< means output.