Open In App

Substring in C++

Last Updated : 18 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • pos: Position of the first character to be copied.
  • len: Length of the sub-string.
  • size_t: It is an unsigned integral type.

Return Value: It returns a string object.

Example:

C++
// 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

  • Time complexity: O(N)
  • Auxiliary Space: O(N)

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: –

  • s.substr(s.begin(),3)  => compilation error 🙂  (because cannnot convert a iterator to a int datatype )
  • s.substr(2,3) =>  llo   (three letter from 2nd index)
  • s.substr(*s.begin()-s[0],3)  => hel   (*s.begin() is ‘h’ then ‘h’-s[0]=> ‘h’-‘h’=0 means substr(0,3) —– three letter from zeroth index
  • s.substr(5,1)  => ‘ ‘  (prints blank space , that is at 5th index)
  • s.substr(2,0)  => (not output)  (selects zero letters from second index)

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
  • Get a Sub-String before a character
  • Print all Sub-Strings of a given String
  • Sum of all Substrings of a string representing a number
  • Print the maximum value of all substrings of a string representing a number
  • Print the minimum value of all substrings of a string representing a number

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++
// 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++
// 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++
// 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++
// 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++
// 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++
// 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

  • Text Searching: Substrings are used to search for words or phrases in larger bodies of text. This is commonly used in search engines, where a user might type in a phrase or keyword and the engine will search for any matches containing that substring.
  • Text Parsing: Substrings are used in text parsing algorithms to break down larger strings into smaller chunks. For example, a parser might be used to extract individual words from a sentence and store them in a data structure.
  • Text Manipulation: Substrings are used in text manipulation applications to find and replace certain words or phrases in larger bodies of text. This can be used to perform search and replace tasks, or to update information in a document.
  • Natural Language Processing: Substrings are used in natural language processing algorithms to identify words and phrases. This is used in applications such as speech recognition, where the algorithm must identify words spoken by a user.
  • Pattern Recognition: Substrings are used in pattern recognition algorithms to identify patterns in data. This can be used to identify trends in financial data, or to detect anomalies in images.
  • Password Security: Substrings are used to verify passwords. This is done by comparing the entered password against a stored substring of the original password. If the two match, then the password is verified. This technique is used in many applications to increase security.


Previous Article
Next Article

Similar Reads

Lexicographical Maximum substring of string
Given a string s we have to find the lexicographical maximum substring of a string Examples: Input : s = "ababaa" Output : babaa Explanation : "babaa" is the maximum lexicographic substring formed from this string Input : s = "asdfaa" Output : sdfaa The idea is simple, we traverse through all substrings. For every substring, we compare it with the
6 min read
Count occurrences of a substring recursively
Given two strings str1 and str2, the task is to count the number of times str2 occurs in str1 using recursion. Examples: Input: str1 = "geeksforgeeks", str2 = "geek"Output: 2Explanation: The occurrences of str2 in str1 are starting at index {0, 8} Input: str1 = "aaaaa", str2 = "aaa"Output: 3Explanation: The occurrences of str2 in str1 are starting
4 min read
Longest substring that starts with X and ends with Y
Given a string str, two characters X and Y. The task is to find the length of the longest substring that starts with X and ends with Y. It is given that there always exists a substring that starts with X and ends with Y. Examples: Input: str = "QWERTYASDFZXCV", X = 'A', Y = 'Z' Output: 5 Explanation: The largest substring which start with 'A' and e
10 min read
Longest substring consisting of vowels using Binary Search
Given string str of length N, the task is to find the longest substring which contains only vowels using the Binary Search technique.Examples: Input: str = "baeicba" Output: 3 Explanation: Longest substring which contains vowels only is "aei".Input: str = "aeiou" Output: 5 Approach: Refer to the Longest substring of vowels for an approach in O(N) c
8 min read
Frequency of a substring in a string | Set 2
Given a string str of length N and a substring pattern of length M, the task is to find the frequency of occurrences of pattern as a substring in the given string. If pattern is present in the string str, then print "Yes" with the count of its occurrence. Otherwise, print "No". Examples: Input: str = "geeksforgeeks", pattern = "geeks"Output: 2Expla
6 min read
Length of the longest substring that contains even number of vowels
Given a string S consisting of N lowercase characters, the task is to find the length of the longest substring consisting of each vowel an even number of times Examples: Input: S= "bcbcbc"Output: 6Explanation:Consider the substring S[0, 5] i.e., "bcbcbc" is the longest substring because all vowels: a, e, i, o and u appear 0(which is even) number of
8 min read
Minimize hamming distance in Binary String by setting only one K size substring bits
Given two binary strings S and T of length N and a positive integer K. Initially, all characters of T are '0'. The task is to find the minimum Hamming distance after choosing a substring of size K and making all elements of string T as '1' only once. Examples: Input: S = "101", K = 2Output: 1Explanation: Initially string T = "000", one possible way
7 min read
Get a Substring in C
Given a string str and pos and len that defines the starting and the length of the subarray. The task is to generate a substring of size len starting from the index pos. A substring is a contiguous sequence of characters within a String. Examples: Input: Str ="the", pos=1, len=2Output: "th"Explanation: substrings will be: "", "t", "h", "e", "th", "
3 min read
Check if given string is a substring of string formed by repeated concatenation of z to a
Given a string str, the task is to check if string str is a substring of an infinite length string S in which lowercase alphabets are concatenated in reverse order as: S = "zyxwvutsrqponmlkjihgfedcbazyxwvutsrqponmlkjihgfedcba...." Examples: Input: str = "cbaz"Output: YES Explanation:Given string "cbaz" is a valid sub string of S. Input: str = "ywxt
10 min read
Longest substring with K unique characters using Binary Search
Given a string str and an integer K, the task is to print the length of the longest possible substring that has exactly K unique characters. If there is more than one substring of the longest possible length, then print any one of them or print -1 if there is no such substring possible. Examples: Input: str = "aabacbebebe", K = 3 Output: 7 "cbebebe
10 min read
Practice Tags :