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

C++ Substring – Questions and Answers

Q 1: What is a substring?

Ans: A part of a string.

Q 2: Which function extracts substring?

Ans: substr().

Q 3: Syntax of substr()?

Ans: str.substr(pos, len)

Q 4: Is length parameter mandatory?

Ans: No.

Q 5: What if position is invalid?

Ans: An exception is thrown.

C++ Substrings – Objective Questions (MCQs)

Q1. Which function is used to extract a substring from a string in C++?






Q2. What is the output of this code?

What is the output of this code?
cout << s.substr(0, 4);






Q3. What does the second parameter of substr(pos, len) represent?






Q4. What happens if the length in substr() exceeds the string size?






Q5. What will be the output of this code?

string s = "HelloWorld";
cout << s.substr(5);






Related C++ Substrings Topics