Understanding Substring Function in C++
The Substring function in C++ is used for handling string operations. This function generates a new string that has its value initialized to a copy of sub-string of this object.
In this article, we will be learning about the Substring function in C++.
Table of Contents
What is a Substring Function in C++?
In C++, the substr() function is a string function that is used to extract a substring from a given string. The function is a member of the std::string class, so it can be used on std::string objects.
Syntax:
The basic syntax for the substr() function is as follows:
string substr (size_t pos = 0, size_t len = npos) const;
Where pos is the starting position of the substring, and len is the length of the substring.
- pos is an integer value that represents the starting position of the substring. The index of the first character in the string is 0. For example, if you want to extract the substring from the 5th character, you would pass 5 as the value for pos.
- len is an integer value that represents the length of the substring. If you do not provide a value for len, the function will return all characters from the pos position to the end of the string.
For example:
std::string str = "Hello World";std::string sub_str = str.substr(6,5);std::cout << "Substring: " << sub_str << std::endl;
This will output:
Substring: World
It’s important to note that, if the position and/or length passed to the substr() function are out of range, it throws an exception of std::out_of_range.
It returns a new std::string object that contains the substring extracted from the original string.
Explore free C++ courses
Best-suited C++ courses for you
Learn C++ with these high-rated online courses
Applications of substr() function in C++
Now let’s take a look at a couple of use cases of the substr() functions in c++.
1. Get the sub-string after a character
In C++, you can use the substr() function to extract a substring from a given string after a specific character. The basic idea is to first find the position of the specific character in the string using the find() function, and then use that position as the starting point for the substr() function.
Here’s an example of how you can extract a substring after a specific character using the substr() function:
#include < iostream > #include < string >
int main(){ std::string str = "Hello World"; std::string sub_str;
// Find the position of the character 'W' size_t pos = str.find('W');
// Extract the substring after the character 'W' if (pos != std::string::npos) { sub_str = str.substr(pos); std::cout < < "Substring after 'W': " < < sub_str < < std::endl; } else { std::cout < < "Character not found in the string." < < std::endl; } return 0;}
Output:
Substring after 'W':World
The find() function is used to search for the character ‘W’ in the string str. If the character is found, find() returns the position of the character. If the character is not found, it returns the special value std::string::npos.
Then the substr() function is used to extract the substring starting from the position of the character ‘W’.
In the above example, we’ve used the find() function to find the position of the character ‘W’ and passed that position as the first parameter to substr() function, to extract the substring after that character, which is “World“. You can use a similar approach to find any specific character and get the substring after that character.
2. Get the sub-string before a character
Similar to the above explanation, we can extract a substring before a specific character using the substr() function:
#include < iostream > #include < string >
int main(){ std::string str = "Hello World"; std::string sub_str;
// Find the position of the character 'W' size_t pos = str.find('W');
// Extract the substring before the character 'W' if (pos != std::string::npos) { sub_str = str.substr(0, pos); std::cout < < "Substring before 'W': " < < sub_str < < std::endl; } else { std::cout < < "Character not found in the string." < < std::endl; } return 0;}
Output:
Substring before 'W':World
Here the substr() function is used to extract the substring ending at the character ‘W’ position.
3. Get all substrings of a given string
In C++, you can use the substring () function to extract all substrings of a given string. To do this, you can use a loop to iterate through all possible starting positions of the substring and use the substr() function to extract the substring of the desired length at each position.
Here’s an example of how you can extract all substrings of a given string of length n using the substr() function:
#include < iostream > #include < string >
int main(){ std::string str = "Hello World"; int n = 3;
for (int i = 0; i < = str.length() - n; i++) { std::string sub_str = str.substr(i, n); std::cout < < sub_str < < std::endl; } return 0;}
Output:
Hel
ell
llo
lo
o W
Wo
Wor
orl
rld
In this example, the outer loop iterates through all possible starting positions of the substring, using the variable i as the index. The substr() function is called inside the loop, with i as the first argument and n as the second argument, where n is the length of the substrings to be extracted. You can change the value of n to get substrings of different lengths. Also, you can use a similar approach to extract all substrings of the string of any length. You should be careful when using this approach on large strings, as it may cause performance issues if the string is too long.
4. Get the sum of all substrings of a string representing a number
In C++, you can use the substr() function to extract all substrings of a given string and then use a loop to iterate through all substrings, converting them to integers using the stoi() function (or atol()), and adding them to a total sum.
Here’s an example of how you can get the sum of all substrings of a string representing a number using the substr() function:
#include < iostream > #include < string >
int main(){ std::string str = "1234"; int sum = 0;
for (int i = 0; i < str.length(); i++) { for (int j = i; j < str.length(); j++) { std::string sub_str = str.substr(i, j-i+1); sum += std::stoi(sub_str); } } std::cout < < "The sum of all substrings is: " < < sum < < std::endl; return 0;}
Output:
The sum of all substrings is: 33
In this example, the outer loop iterates through all possible starting positions of the substring, using the variable i as the index. The inner loop iterates through all possible ending positions of the substring, using the variable j as the index. The substr() function is called inside the inner loop, with i as the first argument and j-i+1 as the second argument, to extract the substring from the starting position i to the ending position j.
Then the stoi() function converts the substring to an integer and adds it to the total sum.
Note that you can also use atol() function to convert string to integer, and the same approach can be used for other types of numbers such as long, double, etc.
In this example, we’ve used a nested loop to iterate through all possible substrings, but you can also use recursion or other methods to get all substrings. You should be careful when using this approach on large strings, as it may cause performance issues if the string is too long.
5. Get Maximum and minimum values of all substrings of a string representing a number
Here’s a C++ program that demonstrates how to find the minimum and maximum of all possible string substrings.
Here’s an example of how you can get the maximum and minimum value of all substrings of a string representing a number using the substr() function:
#include < iostream > #include < string > #include < climits >
int main(){ std::string str = "1234"; int max_value = INT_MIN; int min_value = INT_MAX;
for (int i = 0; i < str.length(); i++) { for (int j = i; j < str.length(); j++) { std::string sub_str = str.substr(i, j-i+1); int value = std::stoi(sub_str); if (value > max_value) { max_value = value; } if (value < min_value) { min_value = value; } } } std::cout < < "The maximum value of all substrings is: " < < max_value < < std::endl; std::cout < < "The minimum value of all substrings is: " < < min_value < < std::endl; return 0;}
Output:
The maximum value of all substring is: 1234
The minimum value of all substring is: 1
This program uses nested loops to iterate through all possible substrings of the given string. In this case, the string is “1234”.
In the outer loop, the variable i is used to iterate through all possible starting positions of the substring. In the inner loop, the variable j is used to iterate through all possible ending positions of the substring. The substr() function is called inside the inner loop, with i as the first argument and j-i+1 as the second argument, to extract the substring from the starting position i to the ending position j.
Then the stoi() function is used to convert the substring to an integer and assign it to the variable value. The code then compares this value with the current maximum and minimum values, stored in max_value and min_value, respectively and updates them accordingly if a new maximum or minimum value is found.
At the end of the loops, all substrings' maximum and minimum values are stored in the max_value and min_value variables, respectively, and printed to the console.
It’s important to note that The program uses the INT_MIN and INT_MAX macros, which are defined in the climits header. These constants represent the minimum and maximum values that can be held in an int variable.
Also, you can use atol() function to convert string to integer, and the same approach can be used for other types of numbers such as long, double etc.
You should be careful when using this approach on large strings, as it may cause performance issues if the string is too long.
Conclusion
A substring in C++ is a portion of a string that can be extracted using the substr() function. The substring function in C++ allows you to extract a specific segment of a string starting from a specified position and of a specified length. This function is commonly used for pattern matching, string manipulation and data extraction in C++.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio