Skip to content

Instantly share code, notes, and snippets.

@Rhomboid
Created November 10, 2012 06:42
Show Gist options
  • Save Rhomboid/4050206 to your computer and use it in GitHub Desktop.
Save Rhomboid/4050206 to your computer and use it in GitHub Desktop.
Removing punctuation from strings in C++98 and C++11
#include <string>
#include <iostream>
#include <cctype>
#include <iterator>
#include <algorithm>
#include <functional>
using namespace std;
int main()
{
string before = "~$foo%(*bar@$|", after;
cout << "before: " << before << endl;
// C++98, remove all punctuation by copying
remove_copy_if(before.begin(), before.end(), back_inserter(after), ptr_fun<int, int>(ispunct));
cout << "after copy (C++98): " << after << endl;
after.erase();
// C++11, remove all punctuation by copying
remove_copy_if(begin(before), end(before), back_inserter(after), [] (char c) { return ispunct(c); });
cout << "after copy (C++11): " << after << endl;
// C++98, remove in place using erase-remove idiom
before.erase(remove_if(before.begin(), before.end(), ptr_fun<int, int>(ispunct)), before.end());
cout << "in-place: " << before << endl;
before = "...don't...";
cout << "before: " << before << endl;
// C++98, remove only leading and trailing punctuation but not interior
// note: this is undefined behavior if the string contains all punctuation
// (that can be fixed by assigning the two iterators to variables and checking that they aren't equal)
after = string(find_if(before.begin(), before.end(), not1(ptr_fun<int, int>(ispunct))),
find_if(before.rbegin(), before.rend(), not1(ptr_fun<int, int>(ispunct))).base());
cout << "after: " << after << endl;
}
$ g++ -Wall -Wextra -pedantic -std=c++11 -O2 20121109.cpp -o 20121109 && ./20121109
before: ~$foo%(*bar@$|
after copy (C++98): foobar
after copy (C++11): foobar
in-place: foobar
before: ...don't...
after: don't
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment