OneBite.Dev - Coding blog in a bite size

Remove A Substring From A String In C++

Code snippet for how to Remove A Substring From A String In C++ with sample and detail explanation

C++ is a versatile language that allows you to manipulate data in a variety of ways. In this article, we will focus on how to remove a substring from a string, an essential operation in handling strings in C++.

Code Snippet: Removing a Substring from a String in C++

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

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

    size_t pos = str.find(to_erase);

    if (pos != string::npos)
    {
        str.erase(pos, to_erase.length());
    }

    cout << str << endl;

    return 0;
}

Code Explanation: Removing a Substring from a String in C++

In this C++ snippet, we are removing a substring from a specific string.

  1. First, we include the necessary headers. In this case, we need iostream for input/output operations and string for string-related operations.

  2. We then declare and initialize our main string str with the value “Hello, world!” and the string to_erase which contains the substring we want to remove from str.

  3. We find the first occurrence of to_erase in str using the find function. This function returns the starting position of the substring to remove. If the find function doesn’t find the substring, it returns string::npos.

  4. We then use an if statement to check if pos is not equal to string::npos, which means to_erase is present in str.

  5. If it is present, we erase the substring using the erase function. The erase function removes a portion of the string, starting from the position given by pos and is of length equal to the length of to_erase.

  6. Finally, we output the result to the console using cout to check if our substring was successfully removed. The string str should now display “Hello, !“.

This is a simple and effective way to remove a substring from a string in C++. It is an essential technique, especially when you need to manipulate and process strings.

c-plus-plus