Open In App

Substring in C++

The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for  std::substr(), string functions is <string>

The substring 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).

 

Syntax: 

string substr (size_t pos, size_t len) const;

Parameters:

Return Value: It returns a string object.

Example:




// C++ program to demonstrate functioning of substr()
#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    // Take any string
    string s1 = "Geeks";
 
    // Copy two characters of s1 (starting
    // from position 3)
    string r = s1.substr(3, 2);
 
    // prints the result
    cout << "String is: " << r;
 
    return 0;
}

Output
String is: ks

More examples:

string: "h  e  l  l  o   w  o  r  l  d"
index:   0 1 2 3 4  5  6  7 8  9 10  

if we write: –

Important Points to Remember

  1. The index of the first character is 0 (not 1).
  2. If pos is equal to the string length, the function returns an empty string.
  3. If pos is greater than the string length, it throws out_of_range. If this happens, there are no changes in the string.
  4. If the requested sub-string len is greater than the size of a string, then returned sub-string is [pos, size()).
  5. If len is not passed as a parameter, then returned sub-string is [pos, size()).

Applications of Substring

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.

Example:




// C++ program to demonstrate functioning of substr()
#include <iostream>
#include <string>
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;
}

Output
String is: cat

Time complexity: O(N)

Auxiliary Space: O(N)                    

How to Get a SubString 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. 

Example:




// C++ program to demonstrate functioning of substr()
#include <iostream>
#include <string>
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
    // Extract everything before the ":" in the string
    // "dog:cat".
    string sub = s.substr(0, pos);
 
    // prints the result
    cout << "String is: " << sub;
 
    return 0;
}

Output
String is: dog

Time complexity: O(N)

Auxiliary Space: O(N)

How to Print all Sub-Strings of a Given String?

Given a string as an input. We need to write a program that will print all non-empty substrings of that given string.

Example:




// C++ program to demonstrate all possible
// substrings of a given string
#include <bits/stdc++.h>
using namespace std;
 
// Function to print all sub strings
void subString(string s, int n)
{
    // Pick starting point in outer loop
    // and lengths of different strings for
    // a given starting point
    for (int i = 0; i < n; i++)
        for (int len = 1; len <= n - i; len++)
            cout << s.substr(i, len) << endl;
}
 
// Driver program to test above function
int main()
{
    string s = "abcd";
    subString(s, s.length());
    return 0;
}

Output
a
ab
abc
abcd
b
bc
bcd
c
cd
d

Time complexity: O( N3 )

Auxiliary Space: O(1)

Print 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.

Example:




// C++ program to print sum of all possible substring of
// a number represented as a string
#include <bits/stdc++.h>
using namespace std;
 
// Utility method to convert character digit to
// integer digit
int toDigit(char ch) { return (ch - '0'); }
 
// Returns sum of all substring of num
int sumOfSubstrings(string s)
{
    vector<int> v;
    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));
            int x = stoi(sub);
            v.push_back(x);
        }
    }
    int res = accumulate(v.begin(), v.end(), 0);
 
    return res;
}
 
// Driver code to test above methods
int main()
{
    string num = "1234";
    cout << sumOfSubstrings(num) << endl;
    return 0;
}

Output
1670

Time Complexity: O(N3)
Auxiliary Space: O(N)

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

Given an integer represented as a string, we need to get the maximum of all possible substrings of the given string which represents a number.

Example:




// C++ program to demonstrate max. of all possible
// substrings of a given string
#include <bits/stdc++.h>
using namespace std;
 
void subString(string s, int n)
{
    vector<int> v;
    for (int i = 0; i < n; i++) {
        for (int len = 1; len <= n - i; len++) {
            string sub = (s.substr(i, len));
            int x = stoi(sub);
            v.push_back(x);
        }
    }
    cout << *max_element(v.begin(), v.end()) << endl;
}
 
// Driver program to test above function
int main()
{
    string s = "823";
    subString(s, s.length());
    return 0;
}

Output
823

Explanation: All substrings are { 8, 82, 823, 2, 23, 3 } and the maximum value substring is 823.

Time complexity: O(N3)

Auxiliary space: O(N!)

Print the Minimum Value of all Substrings of a String Representing a Number

Given an integer represented as a string, we need to get the minimum of all possible substrings of the given string which represents a number.

Example:




// C++ program to demonstrate minimum of all possible
// substrings of a given string
#include <bits/stdc++.h>
using namespace std;
 
void subString(string s, int n)
{
    vector<int> v;
    for (int i = 0; i < n; i++) {
        for (int len = 1; len <= n - i; len++) {
            string sub = (s.substr(i, len));
            int x = stoi(sub);
            v.push_back(x);
        }
    }
    cout << *min_element(v.begin(), v.end()) << endl;
}
 
// Driver program to test above function
int main()
{
    string s = "4572";
    subString(s, s.length());
    return 0;
}

Output
2

Time complexity: O(N3)
Auxiliary space: O(N!)

Other Applications of Substring


Article Tags :