Open In App

substr() in C++

Last Updated : 01 May, 2025
Comments
Improve
Suggest changes
1 Like
Like
Report

In C++, the string substr() function is used to extract a substring from the given string. It generates a new string with its value initialized to a copy of a sub-string of the given string.

Example:


Output
ks

In the above example, we have extracted the last two characters from the string s and stored them in sub string using substr() function.

Syntax of String substr()

The std::string::substr() is the member function of string class defined inside <string> header file.

substr(pos, len);


Parameters:

  • pos: Index of the first character to be copied.
  • len: Length of the sub-string.

Return Value:

  • It returns a string object.

Important Points

  1. The index of the first character is 0 (not 1).
  2. If pos is equal to the string length, the function returns an empty string.
  3. If pos is greater than the string length, it throws out_of_range. If this happens, there are no changes in the string.
  4. If the requested sub-string len is greater than the size of a string, then returned sub-string is [pos, size()).
  5. If len is not passed as a parameter, then returned sub-string is [pos, size()).

Examples of substr()

The following examples illustrates the use of substr() function in C++:

Get a Sub-String after a Character

In this example, a string and a character are given and you have to print the complete sub-string followed by the given character.


Output
String is: cat

Get a SubString Before a Character

This example is a follow-up to the previous one, where we example, we print the complete substring up to a specific character.


Output
String is: dog

Print all Sub-Strings of a Given String

This example is a very famous interview question also. We need to write a program that will print all non-empty substrings of that given string.


Output
a
ab
abc
abcd
b
bc
bcd
c
cd
d

Given an integer represented as a string, we need to get the sum of all possible substrings of this string.


Output
1670


Next Article
Practice Tags :

Similar Reads