I want to delete the first 10 chars from a string in C++. How can I do that?
Use Python to Remove the First N Characters from a String Using Regular Expressions. You can use Python's regular expressions to remove the first n characters from a string, using re's . sub() method. This is accomplished by passing in a wildcard character and limiting the substitution to a single substitution.
Combine RIGHT and LEN to Remove the First Character from the Value. Using a combination of RIGHT and LEN is the most suitable way to remove the first character from a cell or from a text string. This formula simply skips the first character from the text provided and returns the rest of the characters.
Like this:
str.erase(0,10);
...
Use std::string::substr
:
try { str = str.substr(10); } catch (std::out_of_range&) { //oops str is too short!!! }
I suspect that there is more code here that you are not showing, and the problem is likely there.
This code works just fine:
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char **argv)
{
string imgURL = "<img src=\"http://imgs.xkcd.com/comics/sky.png";
string str = imgURL;
int urlLength = imgURL.length();
urlLength = urlLength-10;
str.erase (str.begin(), str.end()-urlLength);
imgURL = str;
cout << imgURL << endl;
return 0;
}
With that said, there are shorter ways to do this, as others have mentioned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With