C++ Programming Language Table of content:
substr() In C++ | Syntax, Use Cases, Tips, & More (+Code Examples)
The substr() function in C++ programming language is one of the string methods used to get a part of the original string. It is a predefined method in the standard library and is used for string slicing and handling other string operations like append(), strcat(), etc. In this blog, we will discuss the syntax, use cases/applications, and more about the substr() function in C++ with the help of examples. So let’s get started!
What Is A Substring In C++ (Substr C++)?
To begin with, a substring refers to a part of the longer string. The substr() function in C++ extracts a portion of a string as a newly constructed string. It’s a member of the std::string class, defined in <string>. It is a powerful tool that helps with string slicing, and it is ideal for extracting substrings for further processing.
The substr in C++ takes two parameters, the starting index and the length of the substring we want from that index, and then it returns a new string object to construct a substring from the original string. Let's take a look at its syntax, components, and return types, followed by an example.
Syntax of substr() Function in C++
string substr(starting_pos, len_substr)
Here:
- The string keyword indicates that the return type of substr() function is a string.
- starting_pos: an unsigned Integer type input parameter. It denotes the position of the first character to be copied from the original string. (Note that the pos parameter is the position parameter, i.e., it refers to the position from which we want the substring to start.)
- len_substr: an unsigned Integer type input parameter denotes the length of the substring.
Return Type
The substr() function in cpp programming returns a newly constructed object of type String, i.e., std::string containing the extracted substring. Case handling:
- If pos equals the string’s length → returns an empty string.
- If pos exceeds the length → throws std::out_of_range.
- If len stretches past the string’s end → grabs characters until the end. No exception.
Example for substr() in C++ | Finding Substring Using Positive and Negative Indices
Let's understand the substr in C++ using the following example:
Output:
Substr1 starting at position 1 and length 6 is: Unstop
Substr2 starting at position 8 and length -2 is: able
Explanation:
We begin by including the <iostream> and <string.h> header files.
- In the main() function, we define a string, originalString, and assign the value "#Unstoppable" to it.
- We then use the C++ substr() to get two substrings of the original:
- In the first case, since the starting index is 1, it implies that the substring1 starts from ‘U’ and ends at the 6th index, which is ‘p’, giving a substring of length 6.
- In the second case, since the length is -2, which is a negative number, the substr function will take all the characters till the end of the string. This is because the parameters of substr() function only take unsigned_integer type values.
- Next, we use the cout statements to print the substrings to the console.
- The results match our expectations: sub1 is exactly six characters from index 1, and sub2 contains everything from index 8 onwards.
- Finally, the main() function closes with a return 0 statement.
Check this out: Boosting Career Opportunities For Engineers Through E-School Competitions
Understanding substr() Basics with Examples
Let’s explore some edge-case examples to better understand how substr() works in C++. Consider a string s = “Unstoppable”. Then the indexes of each character in the sequence of characters in the string will be as follows:
string: U n s t o p p a b l e
index: 0 1 2 3 4 5 6 7 8 9 10
Now consider these cases:
- s.substr(s.begin(), 5)
❌ Compilation Error
Explanation: s.begin() returns an iterator, not an integer. substr() requires an unsigned integer (size_t) as the starting position. - s.substr(2, 3)
✅ Result: "sto"
Explanation: the substr() starts at index 2 ('s') and includes 3 characters: 's', 't', 'o'. - s.substr(*s.begin() - s[0], 6)
✅ Result: "Unstop"
Explanation: *s.begin() yields 'U'; subtracting s[0] (also 'U') equals 0. So, this effectively calls substr(0, 6). - s.substr(2, 0)
✅ Result: "" (empty string)
Explanation: starting at index 2 but taking 0 characters returns an empty string.
Use Cases/ Examples of substr() in C++
The substr() function shines in a variety of real-world string operations, from simple extraction to numeric manipulation. Here's a quick overview of the examples and use cases we'll explore in this section:
- Get a Substring Before a Character: Extracts the part of a string that appears before a specified delimiter.
- All Substrings of a Given String: Iterates through and prints every possible non-empty substring of a string—useful for parsing or analysis tasks
- Sum of All Substrings of a String Representing a Number: Treats each substring as a number and prints the total sum, adding a numeric twist to substring operations.
- Minimum Value of All Substrings of a Numeric String: Finds and outputs the smallest numeric value among all substrings.
- Maximum Value of All Substrings of a Numeric String: Finds and outputs the largest numeric value among all substrings.
- Substring After a Given Character: Extracts the part of a string that appears after a specified delimiter.
Each of these tasks leverages substr() in different ways, demonstrating its versatility—from text parsing to numeric processing. We’ll dive into each example shortly!
How to Get a Substring Before a Character Using substr() in C++?
Let’s assume that you have been given a string and a character. Your task is to print the sub-string followed by the given character. The example below shows how this can be done:
Code Example:
Output:
String is: Hardwork
Explanation:
In this example, we begin with the string s (value "Hardwork:Success")
- We then use the find() function to get the index position of the character (:) and store it in the pos variable.
- Next, we use the substr() function to extract the substring from index 0 to pos.
- Here, we are extracting the substring before the delimiter (:) character.
- We store this substring in the variable sub and then print it to the console using the cout statement.
Use substr() in C++ to Print all Substrings of a Given String
Let’s learn how to obtain all possible substrings from a given string.
Example Code:
Output:
c
co
cod
code
o
od
ode
d
de
e
Explanation:
In this example, we begin by defining a function, subString, which takes a string and an integer as parameters.
- The function uses a set of nested for loops to iterate through the string.
- Here, the outer loop determines the starting point, and the inner loop determines the length of the substring to be extracted.
- In every iteration, we use the substr() function with the cout statement to extract and display the substring to the console.
- In the main() function, we define a string variable, s, with the value "code".
- Then, we call the subString() function, passing the string s, and the length of the string (using length() function) to is as arguments.
- The possible substrings of string “code" are { c, co, cod, code, o, od, ode, d, de, e}. We vary the starting point in the outer loop and the lengths of the substring in the inner loop.
Print Sum of all Substrings of a String Representing a Number
Suppose we have been provided with an integer represented as a string, and we have been asked to get the sum of all possible substrings of this string. We can do this using the following:
Code Example:
Output:
497
Explanation: The number value of all substrings are { 4, 42, 423, 2, 23, 3 }, and the sum of these substrings is 497.
Minimum Value of all Substrings of a String Representing a Number
We have been given an integer represented as a string. Now our task is to get the minimum of all possible substrings of the given string, which is representing a number.
Code Example:
Output
2
Explanation:
All substrings are { 9, 93, 932, 9328, 3, 32, 328, 2, 28, 8 }, and the minimum value substring is 2.
- We define the function subString(), which accepts two parameters: the string s and the length of the string.
- We then create a vector to store the substrings in integer format.
- Next, we use a set of nested for loops to calculate all possible substrings and convert them to integers, subsequently inserting this into a vector.
- We finally find the minimum element, which the function prints to the console using cout.
- In the main() function, we create a string, s, and call the subString() function to get the minimum value.
Maximum Value of all Substrings of a String Representing a Number
We have been given an integer represented as a string. Now our task is to get the maximum of all possible substrings of the given string, which is representing a number.
Example Code:
Output
423
Explanation:
All substrings are { 4, 42, 423, 2, 23, 3 }, and the maximum value substring is 423.
- We define a function subString() that accepts two parameters: the string s and the length of the string.
- Then, we create a vector to store the substrings in integer format.
- Next, we use a set of nested for loops to calculate all possible substrings and convert them to integers, subsequently inserting this into a vector.
- We finally find the maximum element using C++ STL.
Get Substring Before a Specific Character (With substr() and find())
A common requirement is to extract everything that comes after a delimiter within a string—such as getting the file extension, processing key-value pairs, or parsing URLs. You can do this easily by combining .find() and .substr().
Code Example:
Output:
Substring before ':' is: dog
Explanation:
In this example,
- We define a string s with the value “dog:cat”.
- Then, we use the find() function to get the index of a specific character, i.e., s.find(':') returns the index of ':' (here, 3).
- Next, we use the substr() function, i.e., substr(0, pos), which extracts the string from index 0 up to, but does not include index 3.
- We display this to the console using the cout statement, and the main function closes with a return 0 statement.
Points To Remember For Substr In C++
- The index of the first character is always taken as 0 (not 1).
- The starting_pos and substr_len parameters only accept unsigned integer numbers and no other data type.
- If starting_pos equals (=) the original string length, the function returns an empty string.
- If starting_pos is greater than (>) original string length, it throws an ‘out_of_range’ exception, and there are no changes in the string.
- If substr_len is greater than (>) the size of the original string, then the returned sub-string is [starting_pos, size()).
- If substr_len is not passed as a parameter, then the returned sub-string is [starting_pos, size()).
Conclusion
The C++ substr() function, part of the <string> class, is a powerful tool for extracting parts of a string. It takes two unsigned integer parameters: starting position and length. If the length goes beyond the end, it safely returns characters up to the string's end. However, if the starting position exceeds the string length, substr() throws a std::out_of_range exception—so always validate your inputs. In essence, substr() gives you flexible control over string slicing with predictable behavior when used correctly.
Frequently Asked Questions
Q1. What is a substr() in C++?
The substr() is a method of std::string (defined in <string>) that returns a new string. You specify a start index and length, and it slices that part from the original string. The substr function takes two arguments:
- Starting_pos: Indicating the Position of the first character to be copied from the original string.
- Substr_len: Indicates the desired length of the substring from the first position.
Here is the basic syntax of C++ substr() function:
string substr(starting_pos, len_substr)
Q2. How to get a substring of a string in CPP?
To get the substring of a string in CPP, you can use the substr() function. Here is an example:
Output:
Substr
Q3. Do I need to include <string.h> for substr()?
No. Use the C++ string header:
#include <string>
Not the C header <string.h> (or <cstring>), which does not provide std::string.
Q4. Does substr() support negative values?
No. Both parameters are size_t (unsigned). Negative values lead to undefined behavior or compilation error.
Q5. Does substr() include the first character?
Yes. The substring starts exactly at the given index and includes that character, continuing for the specified len.
Q6. What if start equals or exceeds the string length?
- If start == str.size(): returns an empty string.
- If start > str.size(): throws a std::out_of_range exception
Q7. Can I remove part of a string using substr()?
Yes, you can use the substr() function in combination with erase() function to remove a part of the string. Example:
string s = "how are you?";
string del = s.substr(3, 4); // "are "
s.erase(3, del.length());
cout << s; // prints "how you?"
This trims a specified segment out of the string.
Test Your Skills: Quiz Time
QUIZZ SNIPPET IS HERE
QUIZZ SNIPPET IS HERE
QUIZZ SNIPPET IS HERE
You might also be interested in reading the following:
- Pointers in C++ | A Roadmap To All Types Of Pointers With Examples
- Decoding The Difference Between Structure And Class In C++
- Typedef In C++ | Syntax, Application & How To Use It (With Examples)
- C++ String Concatenation | All Methods Explained (With Examples)
- String Compare In C++ | Learn To Compare Strings With Examples