landesko
landesko

Reputation: 372

Remove Punctuation At The End Of A String C++

How do I remove a specific type of punctuation at the end of a string? I want to remove "-" a.k.a. hyphens. I only want to remove them at the end of the string. Thanks.

UPDATE: User Christophe has provided a good solution for those who are using anything less than c++11! The code is below:

for (int n=str.length(); n && str[--n]=='-'; str.resize(n));

Upvotes: 0

Views: 1039

Answers (4)

sjdowling
sjdowling

Reputation: 3022

Boost's solution is worth a mention:

std::string cat = "meow-";
boost::trim_right_if(cat,boost::is_any_of("-"));

demo

Check out the indispensable boost string algo library.

Upvotes: 1

Sam12345
Sam12345

Reputation: 91

Using some useful properties of std::string, namely find_last_of(), find_last_not_of(), substr(), and length():

std::string DeHyphen(const std::string input){
    std::string dehyphened = input;
    if ((dehyphened.length() - 1) == dehyphened.find_last_of("-")) //If we have a hyphen in the last spot,
        return dehyphened.substr(0, dehyphened.find_last_not_of("-")); //Return the string ending in the last non-hyphen character.
    else return dehyphened; //Else return string.
}

Note that this will not work for strings consisting only of hyphens- you will just get the string back. If you want instead an empty string in that instance, simply check for that in the case where the 'if' evaluates true.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490128

std::string has a find_last_not_of member function that makes it easy to find the correct position:

size_t p = your_string.find_last_not_of('-');

From there, it's a simple matter of erasing the content from there to the end of the string:

your_string.erase(pos);

If the string doesn't have any hyphens at the end, the find_last_not_of will return std::string::npos. The overload of erase we're using here takes parameters for both the beginning and ending positions to erase, but sets the end point to std::string::npos as the default. Calling it as your_string.erase(npos, npos) leaves the string unchanged, so we don't need any special code for that case. Since the erase doesn't need to be conditional, you can combine the two pretty easily as well:

your_string.erase(your_string.find_last_not_of('-'));

Upvotes: 0

Christophe
Christophe

Reputation: 73376

Try:

while (str.length() && str.back() == '-') 
    str.pop_back(); 

Upvotes: 4

Related Questions