c++ string slicing

C++ String Slicing Explanation

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

int main() {
    string str = "Hello, World!";
    string sliced = str.substr(7, 5);
    cout << sliced << endl;
    return 0;
}
  • #include \<string> and using namespace std;: Include the necessary libraries for string manipulation and declare the use of the standard namespace.

  • string str = "Hello, World!";: Declare a string variable str and initialize it with the value "Hello, World!".

  • string sliced = str.substr(7, 5);: Use the substr method to extract a substring from index 7 with a length of 5 from the string str and store it in the variable sliced.

  • cout << sliced << endl;: Output the sliced substring to the console.

  • return 0;: Return 0 to indicate successful execution of the program.