S
Spoon
Hello,
I'm writing code to remove .whatever from the end of a string.
e.g. hello.world.foo.bar -> hello.world.foo
The following code seems to work
#include <string>
#include <iostream>
int main(int argc, char **argv)
{
std::string foo(argv[1]);
foo.erase(foo.rfind('.'));
std::cout << foo << std::endl;
return 0;
}
$ ./a.out hello.world.foo.bar
hello.world.foo
but it crashes when rfind() returns npos
$ ./a.out hello+world+foo+bar
terminate called after throwing an instance of 'std:ut_of_range'
what(): basic_string::erase
Aborted
Is pos+1 valid, even when pos==npos?
If so, I could write
#include <string>
#include <iostream>
int main(int argc, char **argv)
{
std::string foo(argv[1]);
foo.erase(foo.rfind('.')+1);
std::cout << foo << std::endl;
return 0;
}
Then I'd have to remove the trailing '.' and the entire string is erased
if there is no '.' (which may be acceptable).
Is there a better solution?
Regards.
I'm writing code to remove .whatever from the end of a string.
e.g. hello.world.foo.bar -> hello.world.foo
The following code seems to work
#include <string>
#include <iostream>
int main(int argc, char **argv)
{
std::string foo(argv[1]);
foo.erase(foo.rfind('.'));
std::cout << foo << std::endl;
return 0;
}
$ ./a.out hello.world.foo.bar
hello.world.foo
but it crashes when rfind() returns npos
$ ./a.out hello+world+foo+bar
terminate called after throwing an instance of 'std:ut_of_range'
what(): basic_string::erase
Aborted
Is pos+1 valid, even when pos==npos?
If so, I could write
#include <string>
#include <iostream>
int main(int argc, char **argv)
{
std::string foo(argv[1]);
foo.erase(foo.rfind('.')+1);
std::cout << foo << std::endl;
return 0;
}
Then I'd have to remove the trailing '.' and the entire string is erased
if there is no '.' (which may be acceptable).
Is there a better solution?
Regards.