 |
C++Talk.NET C++ language newsgroups
|
| View previous topic :: View next topic |
| Author |
Message |
Spoon Guest
|
Posted: Tue Oct 24, 2006 9:11 am Post subject: Remove suffix from string |
|
|
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::out_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. |
|
| Back to top |
|
 |
Kai-Uwe Bux Guest
|
Posted: Tue Oct 24, 2006 9:11 am Post subject: Re: Remove suffix from string |
|
|
Spoon wrote:
| Quote: | 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::out_of_range'
what(): basic_string::erase
Aborted
Is pos+1 valid, even when pos==npos?
|
Yes: the result is of type string::size_type which is unsigned. Unsigned
built-in arithmetic types wrap on overflow.
However, since you have to ask, it relying on it may not be a good idea from
a maintenance point of view: the programmer that comes after you might not
know and get confused (notice that this could easily be yourself a few
months down the road).
| Quote: |
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?
|
What about
foo.erase( std::min( foo.rfind('.'), foo.size() ) );
Best
Kai-Uwe Bux |
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
|