string mystring = "str?in.g!";
How can i remove the punctuation (? . !) from the
string and keep the rest of the characters?
Define a 'filter' as a predicate for std::remove_if() :
#include <string>
#include <algorithm>
#include <iostream>
bool pfilter(std::string::value_type v)
{
std::string punct = "?!.";
std::string::iterator it = punct.begin();
while(it != punct.end())
if(v == *it++)
return true;
return false;
}
int main()
{
std::string s;
while(true)
{
std::cout << "Enter a string <Enter to quit>: ";
std::getline(std::cin, s);
if(s.empty())
break;
s.erase(std::remove_if(s.begin(), s.end(), pfilter),
s.end());
std::cout << "with punctuation removed: "
<< s << std::endl << std::endl;
}
return 0;
}
Test run:
Enter a string <Enter to quit>: str?in.g!
with punctuation removed: string
Enter a string <Enter to quit>: ?s.tri!ng
with punctuation removed: string
Enter a string <Enter to quit>: !s.?tri?ng!
with punctuation removed: string
Enter a string <Enter to quit>: ??str.ing
with punctuation removed: string
Enter a string <Enter to quit>: !?..??
with punctuation removed:
Enter a string <Enter to quit>: string
with punctuation removed: string
Enter a string <Enter to quit>:
[back to OS]
Reference: Josuttis, "The C++ Standard Library
-- A Tutorial and Reference"
(Addison Wesley Longman, 1999)
A very, very, very good book, imo. :-)
HTH,
-Mike
A little for loop calling ispunct wouldn't be too difficult but if you
prefer here's the one line obscure STL solution
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
int main()
{
string str = "str?in.g!";
str.erase(remove_if(str.begin(), str.end(), ispunct), str.end());
cout << str << endl;
return 0;
}
john
> > Define a 'filter' as a predicat
e for std::remove_if() :
>
> #include <string>
> #include <algorithm>
You don't have to work that hard.
#include <cctype>
#include <string>
#include <algorithm>
std::string s = "str?in.g!";
s.erase(std::remove_if(s.begin(),s.end(),std::ispunct),s.end());
--
Welcome to comp.lang.c++: http://www.slack.net/~shiva/welcome.txt
comp.lang.c++ FAQ: http://www.parashift.com/c++-faq-lite/
comp.lang.c FAQ: http://www.eskimo.com/~scs/C-faq/top.html
alt.comp.lang.learn.c-c++: http://www.raos.demon.co.uk/acllc-c++/faq.html
Have you tried it?
But yes, that's how you express an embedded quote
in a string literal. This should be in your C++ text.
std::string punct = "?.!\"";
-Mike
Thanks for all the help guys.