substring function in c++

The substring function in C++ extracts a portion of a string and returns it as a new string. Here's an example of how it works:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello, World!";

    // Using substring function to extract a portion of the string
    string sub = str.substr(7, 5);

    // Outputting the extracted substring
    cout << "Substring: " << sub << endl;

    return 0;
}

Explanation:

  • #include <iostream> and #include <string> are header files included for input/output operations and string handling, respectively.
  • using namespace std; allows the use of elements from the std namespace without explicitly specifying it each time.
  • string str = "Hello, World!"; initializes a string variable str with the value "Hello, World!".
  • string sub = str.substr(7, 5); uses the substr() function on the str string. It takes two parameters:
  • The starting position (7 in this case), which denotes the index where the extraction begins.
  • The length of the substring to be extracted (5 in this case).
  • cout << "Substring: " << sub << endl; outputs the extracted substring sub.