std::string substr
#include <iostream>
#include <string>
int main() {
std::string originalString = "Hello, World!";
// Using substr() to extract a substring starting from index 7
std::string extractedSubstring = originalString.substr(7);
// Displaying the original string and the extracted substring
std::cout << "Original String: " << originalString << std::endl;
std::cout << "Extracted Substring: " << extractedSubstring << std::endl;
return 0;
}
- Include necessary header files:
#include <iostream>
: Includes the input/output stream functions.#include <string>
: Includes the C++ string library.Declare the main function:
int main()
: The main function where program execution begins.Create a string variable:
std::string originalString = "Hello, World!";
: Declares a string variable namedoriginalString
and initializes it with the value "Hello, World!".Use substr() to extract a substring:
std::string extractedSubstring = originalString.substr(7);
: Uses thesubstr()
function to extract a substring fromoriginalString
starting at index 7 (i.e., the eighth character).Display the original string and extracted substring:
std::cout << "Original String: " << originalString << std::endl;
: Outputs the original string to the console.std::cout << "Extracted Substring: " << extractedSubstring << std::endl;
: Outputs the extracted substring to the console.Return 0 to indicate successful execution:
return 0;
: Indicates that the program has executed successfully.