C++ 从字符串中删除第 N 个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12692221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:32:25  来源:igfitidea点击:

Deleting N first chars from string

c++stringcharacter

提问by PTS

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

我想从 C++ 中的字符串中删除前 10 个字符。我怎样才能做到这一点?

回答by Michael Krelin - hacker

Like this:

像这样:

str.erase(0,10);

...

...

回答by PiotrNycz

Use std::string::substr:

使用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/
  1. http://www.cplusplus.com/reference/string/string/substr/

回答by riwalk

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.

话虽如此,正如其他人所提到的,有更短的方法可以做到这一点。