Home »
        C++ STL
    
    Create substring by given start, end index of a string | C ++ STL
    
    
    
    
    
        In this article, we will learn how to create a substring by given start, end index of a string in C++ STL (Standard Template Library)? Here, we will use string header and its inbuilt function to implement the program.
        
            Submitted by IncludeHelp, on August 22, 2018
        
    
    Problem statement
    Given a string, and we have to create a substring from a string, where start and end indexes are given.
    Creating substring by given start, end index
    To copy characters from a given start index to end index, we use substr() function, it is a library function, it is a library function of string header. It returns string object reference.
    Syntax
string& substr(start_index, n);
    Here,
    
        - start_index is the starting index.
- n is the number of characters to be copied.
Here is an example with sample input and output:
Input:
str = "C++ programming language"
start = 2
end = 6
Function  call:
str2 = substring(start, (end-start))
//we have to access 4 characters from 2nd  index
//thus, (end-start) = (6-2) = 4
Output:
str1: "C++ programming language"
str2: "+ pr"
    C++ program to create substring by given start, end index of a string
#include <iostream>
#include <string>
using namespace std;
int main() {
  // declare string and substring
  string str1 = "C++ programming language";
  string str2;
  // star and end index
  int start = 2;
  int end = 6;
  // copy charcters from 2 to 6 index
  str2 = str1.substr(start, (end - start));
  // print strings
  cout << "str1: " << str1 << endl;
  cout << "str2: " << str2 << endl;
  return 0;
}
Output
str1: C++ programming language
str2: + pr
    
    
  
    Advertisement
    
    
    
  
  
    Advertisement