Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax of substr() in C++
3.
Parameters of Substr() in C++ String
4.
Return Value of Substr() in C++
5.
Example For Substr() In C++
5.1.
C++
6.
How does Substr() in C++ Work?
7.
Applications of substr() Function in C++
7.1.
1) Substring After A Character
7.2.
C++
7.3.
2) Substring Before A Character
7.4.
C++
7.5.
3) Print All Substrings 
7.6.
C++
7.7.
4) Get Sum of all Substring of a String Representing a Number
7.8.
C++
7.9.
5) Print the Maximum Value of all Substrings of a String Representing a Number
7.10.
C++
7.11.
6) Print the Minimum Value of all Substring of a String Representing a Number
7.12.
C++
8.
Other Applications of Substring in C++
8.1.
1. Text Searching
8.2.
2. Text Parsing
8.3.
3. Text Manipulation
8.4.
4. Pattern Recognition
8.5.
5. Password Security
8.6.
6. Natural Language Processing
9.
Complexity of Substring in C++
9.1.
Time Complexity 
9.2.
Space Complexity
10.
Frequently Asked Questions
10.1.
What is Substr() C++?
10.2.
How do you use Substr()?
10.3.
How do you find a substring in C++?
10.4.
What type does substr() return C++?
11.
Conclusion
Last Updated: Apr 4, 2024
Easy

Substring in C++

Author Yukti Kumari
1 upvote
gp-icon
Basics of C++
Free guided path
9 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

A string is nothing but a collection of characters like letters, and numbers and special characters like spaces, underscore, etc. In programming, strings play an important role in communication between the users and the program. 
A substring of a string is a contiguous sequence of characters within the string or the sequence of characters between two indices of a string. 

substr c++

We come across many coding problems which require us to deal with substrings, and hence knowing different efficient methods related to substrings can be extremely useful for us. 

An operation that is bound to a string is managed by a " substring " function in the C++ programming language. "substr()," a special function, can remove a specific chunk of a string and utilise it separately. Pos and Len are two crucial parameters that must be supplied in order to use the substr() function correctly. By using "pos," you can define the starting position of the desired substring, and "len" denotes the specific number of characters that the substring above contains.

Syntax of substr() in C++

string substr (size_t pos = 0, size_t len = npos) const;


Here, size_t is the unsigned integral type. 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Parameters of Substr() in C++ String

The function takes two parameters, one is position, and the second one is the length of the substring:

pos 

Position denotes the index of the first character of the substring. 

  • If pos=string length, then the function returns an empty string. 
  • If pos>string length, then the function throws out of range.

len

It denotes the length of the substring. The default value of len is npos, which implies until the end of the string. If the value of len is greater than the length of the string, then substring till the end of the string is returned.

Return Value of Substr() in C++

It returns a newly constructed string object with its value initialized to a copy of a substring of this object.

Example For Substr() In C++

  • C++

C++

#include <iostream>
#include <string.h>
using namespace std;

int main()
{
// Take any string
string s1 = "Welcome to Coding Ninjas";

string r = s1.substr(3, 10);

// prints the result
cout << "String is: " << r;

return 0;
}

 

Output:

String is: come to Co

 

Explanation:

This C++ program defines a program that makes use of the <iostream> and <string> libraries. It creates a string variable s1 with the value "Welcome to Coding Ninjas" and then extracts a substring r with a length of 10 characters beginning with the fourth character (index 3). Finally, the extracted substring r, which is "come to Co," is printed to the console.

How does Substr() in C++ Work?

Working of substr() function in C++ is as follows:

  • To extract a substring from a specified string in C++, we use the substr() method. In C++, a substring is a segment of a string
     
  • The position and length parameters are passed to the substr() method
     
  • The starting position of the substring in the given string is represented by the argument position
     
  • The parameter length represents the number of characters to obtain from the specified string in the substring
     
  • The substr() function returns the substring retrieved from the given string beginning at the specified point and continuing up to the number of characters specified as length from the starting place

Applications of substr() Function in C++

There are many applications is substr() function in C++. Some of them are:

1) Substring After A Character

Let's see the code for finding the substring after a particular character in a given string. First, we find the character's position in the string and use this position to get the substring. We don't pass the second parameter to the function substr to get the entire substring after the character’s position.

Example - 

If string = “coding_ninjas”, and the character is ‘_’, then the substring will be “ninjas”.

substring after character

Code in C++

  • C++

C++

/*C++ program to find substring after a character in a string*/
#include <string.h>
#include <iostream>
using namespace std;

void findSubstrAfterChar(string input, char c)
{
  // Finding position of '_' using find()
  int position = input.find(c);

  // Finding the substring after position
  string substring = input.substr(position + 1);

  // printing the resulting substring
  cout << "The substring after the character "<<c<<" is: " << substring << endl;
}

int main()
{
  string input = "coding_ninjas";
  findSubstrAfterChar(input, '_');
  //non-existing character, colon not present in the string
  findSubstrAfterChar(input, ':');
  findSubstrAfterChar(input, 'i');
  findSubstrAfterChar(input, 's');
  return 0;
}

 

Output

The substring after the character _ is: ninjas
The substring after the character : is: coding_ninjas
The substring after the character i is: ng_ninjas
The substring after the character s is: 

 

Explanation

In the input string, “coding_ninjas”:

  • After the character ‘_’, the substring is “ninjas”.
     
  • The character ‘:’ is not present in the string, so we can see that the output is the whole input string itself.
     
  • The character ‘i’ occurs multiple times in the input string, but you will get the substring after the first occurrence of the character. Hence the output is “ng_ninjas”.
     
  • It gives an empty string if we pass the last character of the input string.

2) Substring Before A Character

We can find the substring before a particular character by finding the character's position in the string. Then we pass starting position = 0 and length as the position of the character to get the desired substring.
Example - 

If string = “coding_ninjas” and the character is ‘_’, then the substring will be “coding”.

substring before character

Let's look at the code below for a clear understanding.

Code in C++

  • C++

C++

/*C++ program to find substring before a character in a string*/
#include <string.h>
#include <iostream>
using namespace std;

void findSubstrBeforeChar(string input, char c)
{
  // Finding position of '_' using find()
  int position = input.find(c);

  // Finding the substring after position
  string substring = input.substr(0, position);

  // printing the resulting substring
  cout << "The substring before the character "<<c<<" is: " << substring << endl;
}

int main()
{
  string input = "coding_ninjas";
  findSubstrBeforeChar(input, '_');
  //non-existing character, colon not present in the string
  findSubstrBeforeChar(input, ':');
  findSubstrBeforeChar(input, 'i');
  return 0;
}

 

Output

The substring before the character _ is: coding
The substring before the character : is: coding_ninjas
The substring before the character i is: cod

 

Explanation

In the input string, “coding_ninjas” we can see that:

  • The substring before that character ‘_’ is coding.
     
  • The character ‘:’ is not present in the string, so if we try to find the substring before this character, we get the input string as the output.
     
  • The substring before the first occurrence of the character ‘i’ is “cod”.

3) Print All Substrings 

There can be a total of n*(n-1) substrings in a given string. We can find all the substrings of a string using two for loops. The outer loop iterates over all the indices of the string, which serve as the starting position of the substring, and the inner loop denote the length of the substring, which can vary from 1 to string_length-current_index. 

Code in C++

  • C++

C++

/* C++ program to print all the substrings of a given string*/
#include <string.h>
#include <iostream>
using namespace std;

// Function for printing all substrings
void printAllSubstrings(string s)
{
int length = s.length();
for (int i = 0; i < length; i++)
{
for (int currLen = 1; currLen <= length - i; currLen++)
{
cout << s.substr(i, currLen) << endl;
}
}
}

int main()
{
string s = "ninja";
printAllSubstrings(s);
return 0;
}

 

Output

n
ni
nin
ninj
ninja
i
in
inj
inja
n
nj
nja
j
ja
a

 

Explanation

In the given string s= “ninja”, first we fix a string index through the outer loop, and in the inner loop, we find the substrings of all possible lengths from the current starting index. We get a total of n*(n-1) substrings where n=length of the string.

4) Get Sum of all Substring of a String Representing a Number

To obtain all substrings from the original string, we will iterate over it and extract all possible combinations. The sums of all possible substrings are received, with each substring handled as an individual integer. In this, we treat each digit as the substring's last digit. 

Code in C++

  • C++

C++

#include <bits/stdc++.h>
using namespace std;

//function to convert char to int
int CharToInt(char ch) {
return (ch - '0');
}

//function that returns all substring
int Substring_Sum(string inputNum) {
int length = inputNum.length();
int pValue = CharToInt(inputNum[0]);
int answer = pValue;
int c_Sum = 0;

//iterate through characters
for (int i = 1; i < length; i++) {
int c_Digit = CharToInt(inputNum[i]);
c_Sum = (i + 1) * c_Digit + 10 * pValue;

answer += c_Sum;
pValue = c_Sum;
}

//return final sum of all the possible substring
return answer;
}

int main() {
string userInput;
cout << "Enter a numeric string: ";
cin >> userInput;

int substringSum = Substring_Sum(userInput);

cout << "The sum of all substrings for the input string \"" << userInput << "\" is: " << substringSum << endl;

cout << "Coding Ninjas rocks! Happy coding!" << endl;

return 0;
}

 

Output

Enter a numeric string: 158
The sum of all substrings for the input string "158" is: 245
Coding Ninjas rocks! Happy coding!

 

Explanation

Each time the program loops through a digit in the string, it combines the latest value to the previous value and multiplies the digit by wherever it occurs in the string to arrive at the total. As a demonstration, "158" was selected as the input string. Then this input's sub strings will be {1, 5, 8, 15, 58, and 158}.

5) Print the Maximum Value of all Substrings of a String Representing a Number

This code will help you find the most significant value across all the possible substrings of a given input string. The code determines and outputs the maximum value found within the substrings by obtaining input from the user.

Code in C++

  • C++

C++

#include <bits/stdc++.h>
using namespace std;

//function to find maximum value among all substrings
void findMaximumSubstringValue(const string & s) {
vector <int> values;

//reaching for all possible substrings
for (int i = 0; i < s.length(); i++) {
for (int len = 1; len <= s.length() - i; len++) {
string sub_str = s.substr(i, len);
int value = stoi(sub_str);
values.push_back(value);
}
}

if (values.empty()) {
cout << "No valid substrings found." << endl;
} else {
cout << "The maximum value among all substrings is: " << * max_element(values.begin(), values.end()) << endl;
}
}

int main() {
string s;
cout << "Enter a string: ";
cin >> s; // Input the string from the user
findMaximumSubstringValue(s); // Call the function to find the maximum value among substrings
return 0;
}

 

Output

Enter a string: 74558
The maximum value among all substrings is: 74558

 

Explanation

We generate a collection of integer substrings by storing them in a vector. Through iterating using a loop, we encompass all possible substrings, convert them to integers, and append them to the vector. Eventually, the C++ STL is utilized to determine the maximum element. As an example, considering the string "74536," the following substrings are possible: "7", "4", "5", "3", "6", "74", "45", "53", "36", "745", "453", "536", "7453", "4536", and "74536" with the maximum value being 74536.

6) Print the Minimum Value of all Substring of a String Representing a Number

This code will help you find the minimum value across all the possible substrings of a given input string. The code determines and outputs the minimum value found within the substrings by obtaining input from the user.

Code in C++

  • C++

C++

#include <bits/stdc++.h>
using namespace std;

//function to find minimum value among all substrings
void printMinimumSubstringValue(const string & s) {
vector <int> values;

//reaching for all possible substrings
for (int i = 0; i < s.length(); i++) {
for (int len = 1; len <= s.length() - i; len++) {
string sub_str = s.substr(i, len);
int value = stoi(sub_str);
values.push_back(value);
}
}

if (values.empty()) {
cout << "No valid substrings found." << endl;
} else {
cout << "The minimum value among all substrings is: " << * min_element(values.begin(), values.end()) << endl;
}
}

int main() {
string s;
cout << "Enter a string representing a number: ";
cin >> s;
printMinimumSubstringValue(s);
return 0;
}

 

Output

Enter a string representing a number: 74536
The minimum value among all substrings is: 3

 

Explanation

We generate a collection of integer substrings by storing them in a vector. Through iterating using a loop, we encompass all possible substrings, convert them to integers, and append them to the vector. Eventually, the C++ STL is utilized to determine the smallest element. As an example, considering the string "74536," the following substrings are possible: "7", "4", "5", "3", "6", "74", "45", "53", "36", "745", "453", "536", "7453", "4536", and "74536" with the minimum value being 3.

Other Applications of Substring in C++

There are many applications of substring some of them are as follows:

1. Text Searching

By extracting substrings from larger texts or documents and comparing them to desired search terms, you can identify exact patterns or keywords and retrieve relevant information.

2. Text Parsing

 The breaking down of difficult text or structured data into smaller, easier-to-manage parts becomes possible using substring manipulation. This method proves useful for tasks like extracting certain fields from a text or looking at specific dataset things.

3. Text Manipulation

Substrings enable text to be changed or converted. The collection and replacement of specific substrings can be used to format text, clean up data, and change the content.

4. Pattern Recognition

The analysis of substrings helps recognize patterns and sequences within text or data. Examining the relationships between substrings allows one to unveil recurring trends applicable in various fields, such as data mining, bioinformatics, and image processing.

5. Password Security

Substring analysis can improve password security by detecting common patterns or substrings in passwords, reducing weak or readily guessable passwords, and increasing overall safety.

6. Natural Language Processing

Substrings are used in various natural language processing activities, including language modeling and machine translation. They are used to break down phrases into smaller pieces for analysis and to recognize specific linguistic structures.

Complexity of Substring in C++

The complexity of substring operations in C++ refers to the efficiency and performance of extracting a portion of a string.

Time Complexity 

The function's time complexity is O(n), where n is the length of the input string.

Space Complexity

The space complexity of the function is O(n), where n is the length of the input string because it constructs a new string for returning the substring whose maximum length can be equal to the length of the input string.

Frequently Asked Questions

What is Substr() C++?

The substr() method in C++ is a predefined string class function that extracts a discrete segment (substring) from a supplied string. The substr() function accepts two arguments: the beginning index, which indicates where the selected substring begins, and the length of the substring.

How do you use Substr()?

A part of characters within a string is known to as a substring in C++. The substr() function in C++ extracts substrings and requires two parameters: pos and len. The pos parameter gives the selected substring's starting point, while the character length is given by len.

How do you find a substring in C++?

In C++, you can find a substring within a string using the find() method, which returns the position of the first occurrence of the substring. If not found, it returns string::npos.

What type does substr() return C++?

The substr() method returns a new string containing a substring of the original string, based on the provided starting position and length.

Conclusion

In this article, we learned about Substring in C++, the library function substr C++ and its behavior in different cases, and the use cases of substrings, along with examples.

We hope that this blog has helped you enhance your knowledge regarding substring in C++.

Related Articles -

To learn more about Data Structures and Algorithms, you can enroll in our DSA in C++ Course. Do upvote our blog to help other ninjas grow.

Happy Reading!!‍

Previous article
Message Passing in C++
Next article
Mutating & Non-Mutating algorithms in C++
Guided path
Free
gridgp-icon
Basics of C++
9 chapters
104+ Problems
gp-badge
Earn badges and level up
Live masterclass