Substring in C++
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 starts from pos and is done till pos+len means [pos, pos+len).
Important points:
- 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 happens, there are no changes in the string.
- If the requested sub-string len is greater than the size of a string, then returned sub-string is [pos, size()).
- If len is not passed as a parameter, then returned sub-string is [pos, size()).
Syntax:
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.
CPP
// CPP program to illustrate substr() #include <string.h> #include <iostream> using namespace std; int main() { // Take any string string s1 = "Geeks" ; // Copy three characters of s1 (starting // from position 1) string r = s1.substr(1, 3); // prints the result cout << "String is: " << r; return 0; } |
Output:
String is: eek
Applications :
- How to get a sub-string after a character?
In this, a string and a character are given and you have to print the sub-string followed by the given character.
Extract everything after the “:” in the string “dog:cat”.
C++
// CPP program to illustrate substr() #include <string.h> #include <iostream> using namespace std; int main() { // Take any string string s = "dog:cat" ; // Find position of ':' using find() int pos = s.find( ":" ); // Copy substring after pos string sub = s.substr(pos + 1); // prints the result cout << "String is: " << sub; return 0; } |
String is: cat
2. How to get a sub-string before a character?
In this, a string and a character are given and you have to print the sub-string followed by the given character.
Extract everything before the “:” in the string “dog:cat”.
CPP
// CPP program to illustrate substr() #include <string.h> #include <iostream> using namespace std; int main() { // Take any string string s = "dog:cat" ; // Find position of ':' using find() int pos = s.find( ":" ); // Copy substring before pos string sub = s.substr(0 , pos); // prints the result cout << "String is: " << sub; return 0; } |
String is: dog
3. Print all substrings of a given string
4. Sum of all substrings of a string representing a number