Alex Rivera | Logout

Deleting N first chars from string

Asked 2012-10-02T14:25:49.887
31

I want to delete the first 10 chars from a string in C++. How can I do that?

Edit
Report

2 Answers

9

Use std::string::substr:

try {
   str = str.substr(10);
} catch (std::out_of_range&) {
     //oops str is too short!!!
}
  1. http://www.cplusplus.com/reference/string/string/substr/
answered 2012-10-02T14:32:43.560
1

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.

answered 2012-10-02T14:40:52.423

Your Answer