Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting N first chars from string

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

like image 633
timonsku Avatar asked Oct 02 '12 14:10

timonsku


People also ask

How do I remove the first 5 characters in Python?

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.

How do I remove the first n characters from a string in Excel?

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.


3 Answers

Like this:

str.erase(0,10); 

...

like image 171
Michael Krelin - hacker Avatar answered Oct 14 '22 14:10

Michael Krelin - hacker


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/
like image 40
PiotrNycz Avatar answered Oct 14 '22 13:10

PiotrNycz


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.

like image 33
riwalk Avatar answered Oct 14 '22 12:10

riwalk