by Sai gowtham

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.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course