468,513 Members | 1,403 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,513 developers. It's quick & easy.

std::string remove the last character if its a '/'

14
hi,
how do I remove the last character in a string only if its a "/". otherwise no need to remove the last character.

im using std::string. tried with find_last_of( ).

thanks
rsennat
Feb 4 '08 #1
3 29515
rsennat
14
Is this efficient,
Expand|Select|Wrap|Line Numbers
  1. size_t pos = Path.find_last_of("/");
  2. if(pos == Path.length()-1)
  3. {
  4.     Path.erase(Path.length()-1);
  5. }
  6.  
hi,
how do I remove the last character in a string only if its a "/". otherwise no need to remove the last character.

im using std::string. tried with find_last_of( ).

thanks
rsennat
Feb 4 '08 #2
weaknessforcats
9,207 Expert Mod 8TB
No.

You should find_last_of() and check the value of pos afterwards, it if is string::npos, the / was not found. Please do not assume that -1 means not found.

Otherwise, the / was found and you can erase the character at the location where it was found:
Expand|Select|Wrap|Line Numbers
  1. string::size_type pos = Path.find_last_of("/");
  2. if(pos !=string::npos)
  3. {
  4.     Path.erase(pos);
  5. }
  6.  
Feb 4 '08 #3
Sorry weaknessforcats, it seems that you didn't understand rsennat's question.

The question was about about last character in a string whatever it is and not about last occurrence of '/' character. You code will remove '/' even if it is found in the middle of string.

The correct code is:

Expand|Select|Wrap|Line Numbers
  1. if (path.length() > 0)
  2. {
  3.     std::string::iterator it = path.end() - 1;
  4.     if (*it == '/')
  5.     {
  6.          path.erase(it);
  7.     }
  8. }
  9.  
Apr 27 '11 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

11 posts views Thread by Christopher Benson-Manica | last post: by
1 post views Thread by Chris Mantoulidis | last post: by
18 posts views Thread by JKop | last post: by
1 post views Thread by Tero Toivanen | last post: by
8 posts views Thread by Jason Heyes | last post: by
7 posts views Thread by JustSomeGuy | last post: by
4 posts views Thread by Jim Langston | last post: by
3 posts views Thread by Jim Langston | last post: by
2 posts views Thread by darkkal | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.