how can I delete a substring from a string in c++?

To delete a substring from a string in C++, you can follow these steps:

  1. Include the necessary headers: Begin by including the necessary headers for string manipulation in C++. You will need the <string> header for working with strings.
#include <string>
  1. Declare and initialize the string: Declare a string variable and initialize it with the original string that contains the substring you want to delete.
std::string originalString = "Hello World";
  1. Find the position of the substring: Use the find() function to find the starting position of the substring within the original string. The find() function returns the position of the first occurrence of the substring in the string, or std::string::npos if the substring is not found.
size_t pos = originalString.find("World");
  1. Delete the substring: If the substring is found, you can use the erase() function to remove the substring from the original string. The erase() function takes two arguments: the starting position of the substring to be erased and the length of the substring. In this case, you can pass the pos variable as the starting position and the length of the substring you want to delete.
if (pos != std::string::npos) {
    originalString.erase(pos, 5);
}
  1. Output the modified string: Finally, you can output the modified string to verify that the substring has been deleted.
std::cout << originalString << std::endl;

Putting it all together, here's the complete code:

#include <iostream>
#include <string>

int main() {
    std::string originalString = "Hello World";
    size_t pos = originalString.find("World");

    if (pos != std::string::npos) {
        originalString.erase(pos, 5);
    }

    std::cout << originalString << std::endl;
    return 0;
}

This code will output "Hello" as the modified string, with the substring "World" deleted.