Removing the first n characters of a string in C++
In this tutorial, we are going to learn about how to remove the first n characters of a string in C++.
Consider, we have the following string.
string fruit = "apple";
Now, we want to remove the first 3 characters app
from the above string.
Removing the first n characters
To remove the first n characters of a string, we can use the built-in erase()
function by passing the 0, n
as arguments to it.
Where 0
is the first character index, n is the number of characters we need to remove from the index 0.
Here is an example, that removes the first 3 characters from the following string:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string fruit = "apple";
fruit.erase(0,3); // removes first 3 characters
cout<< fruit;
return 0;
}
Output:
"le"
Note: The erase() function modifies the original string instead of creating a new string.
You can also remove the first 2 characters of a string like this:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string fruit = "apple";
fruit.erase(0,2); // removes first 2 characters
cout<< fruit;
return 0;
}
Alternatively, we can use the substr()
function to remove the first n characters of a string in C++.
Here is an example, that removes the first 3 characters of a string:
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string fruit = "apple";
string result = fruit.substr(3);
cout<< result;
return 0;
}
In the above code, we have passed 3
to the substr()
function so that it begins the extraction at index 3 to the end of a string.
Note: The substr() function returns a new string with the specified characters instead of modifying the original string.