2

Is there a way to remove punctuation specifically from the beginning and end of a string, while leaving contractions and possessives alone?

e.g "!wow!" would become "wow" and "can't" would stay "can't"

bfriz_96
  • 53
  • 4
  • 6
    Certainly. It will, however, require code I'm afraid. How'd yours turn out? (I'm assuming not so well, otherwise you wouldn't be here). Perhaps post it *in your question* and we can see where the problem is? – WhozCraig Oct 26 '16 at 15:13
  • This post may be of use: http://stackoverflow.com/a/25385766/3807729 not sure it qualifies as a duplicate or not. – Galik Oct 26 '16 at 15:22
  • I've tried erasing the character at the index, but that throws an error because the index is thereby empty. – bfriz_96 Oct 26 '16 at 17:57

1 Answers1

8

You can do that with boost::trim_if:

std::string a = "!wow!";
boost::trim_if(a, [](char c) { return std::ispunct(c); });
std::cout << a << '\n';

Outputs:

wow
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • Not too familiar with boost. Is there an article where I could learn more about using it in this context? Or is there a more universal option? – bfriz_96 Oct 26 '16 at 17:45
  • @bfriz_96 Nothing quite so elegant. You could [`find_first_not_of`](http://en.cppreference.com/w/cpp/string/basic_string/find_first_not_of) and [`find_last_not_of`](http://en.cppreference.com/w/cpp/string/basic_string/find_last_not_of) and get the [`substr`](http://en.cppreference.com/w/cpp/string/basic_string/substr) between them – user4581301 Oct 26 '16 at 18:55
  • @bfriz_96 Here is an overview/tutorial for boost string algos: http://www.boost.org/doc/libs/1_62_0/doc/html/string_algo/usage.html – Maxim Egorushkin Oct 27 '16 at 13:13