Removing the first n characters of a string in C++
In this post we will give you information about Removing the first n characters of a string in C++. Hear we will give you detail about Removing the first n characters of a string in C++And how to use it also give you demo for it if it is necessary.
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.
Hope this code and post will helped you for implement Removing the first n characters of a string in C++. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs