Last Updated : 19 May, 2025
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:
C++
#include <iostream>
#include <string>
using namespace std;
int main() {
// Take any string
string s = "Geeks";
// Extract two characters of s1 (starting
// from index 3)
string sub = s.substr(3, 2);
cout << sub;
return 0;
}
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.
C++
Parameters:
Return Value:
The following examples illustrates the use of substr() function in C++:
Get a Sub-String after a CharacterIn this example, a string and a character are given and you have to print the complete sub-string followed by the given character.
C++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "dog:cat";
// Find position of ':' using find()
int pos = s.find(":");
// Extract substring after pos
string sub = s.substr(pos + 1);
cout << "Substring is: " << sub;
return 0;
}
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.
C++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "dog:cat";
// Find position of ':' using find()
int pos = s.find(":");
// Copy substring before pos
// Extract everything before the ":" in the string
// "dog:cat".
string sub = s.substr(0, pos);
cout << "Substring is: " << sub;
return 0;
}
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.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
string s = "abcd";
// subString(s, s.length());
int n = s.length();
// Logic to print all substring
// using substr()
for (int i = 0; i < n; i++)
for (int len = 1; len <= n - i; len++)
cout << s.substr(i, len) << endl;
return 0;
}
a ab abc abcd b bc bcd c cd dPrint Sum of all Substrings of a String Representing a Number
Given an integer represented as a string, we need to get the sum of all possible substrings of this string.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
string s = "1234";
int res = 0;
int n = s.length();
for (int i = 0; i < n; i++) {
for (int len = 1; len <= n - i; len++) {
string sub = (s.substr(i, len));
// Convert the substring into
// integer number
int x = stoi(sub);
res += x;
}
}
cout << res;
return 0;
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4