Substring in C++


A substring is a part of a string. A function to obtain a substring in C++ is substr(). This function contains two parameters: pos and len. The pos parameter specifies the start position of the substring and len denotes the number of characters in a substring.

A program that obtains the substring in C++ is given as follows −

Example

 Live Demo

#include <iostream>
#include <string.h>

using namespace std;
int main() {
   string str1 = "Apples are red";
   string str2 = str1.substr(11, 3);
   string str3 = str1.substr(0, 6);

   cout << "Substring starting at position 11 and length 3 is: " << str2 <<endl;
   cout << "Substring starting at position 0 and length 6 is: " << str3;
   return 0;
}

Output

The output of the above program is as follows −

Substring starting at position 11 and length 3 is: red
Substring starting at position 0 and length 6 is: Apples

In the above program, str1 is declared as "Apples are red". Then str2 stores the substring of str1 that starts at position 11 and is of length 3. Also, str3 stores the substring of str1 that starts at position 0 and is of length 6. This is given below −

string str1 = "Apples are red";
string str2 = str1.substr(11, 3);
string str3 = str1.substr(0, 6);

The contents of str2 and str3 are displayed. The code snippet for this is given as follows −

cout << "Substring starting at position 11 and length 3 is: " << str2 <<endl;
cout << "Substring starting at position 0 and length 6 is: " << str3;

Updated on: 07-Oct-2023

22K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements