Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

for_each & copy algorithm

Status
Not open for further replies.

bterribi

Programmer
Sep 27, 2006
8
US
/* Hello, I'm attempting to write the function body for removePunctuation w/o loops. I've been playing around w/ the for_each algorithm to remove punctuation from a string s (which seems to be working fine), then copy the results into a new string t. For example, convert "a*^^bc__" to "abc" However, I'm not getting the desired results using the copy algorithm. Does anyone have any suggestions?*/

#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
bool isLetter(char c);
string removePunctuation (string s);
int main()
{
string s1="a*^^bc__";
string s2=removePunctuation(s1);;
cout<<"s2="<<s2<<endl;
system("pause");
return 0;
}
bool isLetter(char c)
{
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
string removePunctuation (string s)
{
string t;

for_each(s.begin(), s.end(), isLetter);
copy(s.begin(), s.end(), back_inserter(t));

return t;
}
 
Code:
bool isLetter(char c)
{
  return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
This is the incorrect way to check for a character since it's only guaranteed to work properly on ASCII systems.
Use isalpha() instead.

You may want to look into the remove_copy_if() algorithm instead.
 
//Thanks...remove_copy_if got the job done!

bool isLetter(char c)
{
return !((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'));
}

string removePunctuation (string s)
{
string t;
remove_copy_if(s.begin(), s.end(), back_inserter(t), isAlphabetic);
return t;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top