-
string methods hard time
Hello people,
can anyone explain me why output from this program
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "This is, you shouldn't see this, just a test!";
string :: size_type start, end;
string delim = ",";
start = str.find(delim);
if (start == string::npos)
{
return 0;
}
end = str.find(delim, start+delim.length());
str.erase(start, end+delim.length());
cout << str;
return 0;
}
is: "This is test!"(without quotes)?
I expected that characters between ',' (including them) would be removed.
-
The reason is that the erase() member function of std::string usually uses iterators. In your case, you are using the version that is index-based. This version takes a starting index, followed by the number of characters to erase.
You could simply switch to the iterator version:
Code:
str.erase(str.begin() + start, str.begin() + end + delim.length());
-
Or to use this:
Code:
str.erase(start, end+delim.length()-start);
Thanks laserlight, I didn't pay attention when reading documentation.