In C++, std::substr() is a predefined function used for string handling. string.h is the header file required for string functions.
This function takes two values pos and len as an argument and returns a newly constructed string object with its value initialized to a copy of a sub-string of this object. Copying of string start from pos and done till pos+len means [pos, pos+len).
- The index of the first character is 0 (not 1).
- If pos is equal to the string length, the function returns an empty string.
- If pos is greater than the string length, it throws out_of_range. If this happen, there are no changes in the string.
- If for the requested sub-string len is greater than size of string, then returned sub-string is [pos, size()).
string substr (size_t pos, size_t len) const; Parameters: pos: Position of the first character to be copied. len: Length of the sub-string. size_t: It is an unsigned integral type. Return value: It returns a string object.
String is: eek
- How to get sub-string after a character?
In this a string and a character is given and you have to print the sub-string followed by the given character.
Extract everything after the “:” in the string “dog:cat”.
// CPP program to illustrate substr()
// Take any string
string s =
// Find position of ':' using find()
pos = s.find(
// Copy substring after pos
string sub = s.substr(pos + 1);
// prints the result
"String is: "
String is: cat
- Print all substrings of a given string
- Sum of all substrings of a string representing a number
- Print substring of a given string without using any string function and loop in C
- Lexicographical Maximum substring of string
- Count occurrences of a substring recursively
- Longest substring that starts with X and ends with Y
- Check if given string is a substring of string formed by repeated concatenation of z to a
- Custom Jumble Word Game
- Comparator Class in C++ with Examples
- Complete Guide to Install C++17 in Windows
- Features of C++
- Draw a triangle in C++ graphics
- Implementation of lower_bound() and upper_bound() in List of Pairs in C++
- How to Setup VSCode with C, C++ and Python for Competitive Programming
- Java System.exit(0) vs C++ return 0
- Features of C++17 with Examples
This article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.