The Wayback Machine - https://web.archive.org/web/20240828112957/https://www.geeksforgeeks.org/substring-in-cpp/
Open In App

Substring in C++

Last Updated : 05 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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: Index 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 index 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
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
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
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
Print substring of a given string without using any string function and loop in C
Write a function mysubstr() in C that doesn't use any string function, doesn't use any loop, and prints substring of a string. The function should not modify contents of string and should not use a temporary char array or string. For example mysubstr("geeksforgeeks", 1, 3) should print "eek" i.e., the substring between indexes 1 and 3. One solution
2 min read
Print all occurrences of a string as a substring in another string
Given two strings, str1 and str2, the task is to print the indices(Consider, indices starting from 0) of the occurrence of str2 in str1. If no such index occurs, print "NONE". Examples: Input : GeeksforGeeks GeeksOutput : 0 8Input : GFG gOutput : NONEApproach 1 (Naive Approach): A simple solution is to check all substrings of a given string one by
12 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
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
30 OOPs Interview Questions and Answers (2024)
Object-Oriented Programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
C Programs
C Programs: Practicing and solving problems is the best way to learn anything. Here, we have provided 100+ C programming examples in different categories like basic C Programs, Fibonacci series in C, String, Array, Base Conversion, Pattern Printing, Pointers, etc. These C programs are the most asked interview questions from basic to advanced level.
9 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations.  As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example,  If there is
9 min read
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 &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Polymorphism
The word "polymorphism" means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person ex
7 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
9 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Priority Queue in C++ Standard Template Library (STL)
A C++ priority queue is a type of container adapter, specifically designed such that the first element of the queue is either the greatest or the smallest of all elements in the queue, and elements are in non-increasing or non-decreasing order (hence we can see that each element of the queue has a priority {fixed order}). In C++ STL, the top elemen
11 min read
Vector in C++ STL
Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inse
10 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the &lt;map&gt; header file. Basic std::map Member FunctionsSome basic functions associated with std::
8 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
9 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&amp;T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read
Practice Tags :