I want to delete the first 10 chars from a string in C++. How can I do that?
我想从C ++中的字符串中删除前10个字符。我怎样才能做到这一点?
3 个解决方案
#1
25
Like this:
str.erase(0,10);
...
#2
5
Use std::string::substr
:
try {
str = str.substr(10);
} catch (std::out_of_range&) {
//oops str is too short!!!
}
#3
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.
话虽如此,正如其他人所提到的那样,有更短的方法可以做到这一点。
#1
25
Like this:
str.erase(0,10);
...
#2
5
Use std::string::substr
:
try {
str = str.substr(10);
} catch (std::out_of_range&) {
//oops str is too short!!!
}
#3
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.
话虽如此,正如其他人所提到的那样,有更短的方法可以做到这一点。