easy way to remove unwanted characters from a string?

I want to remove every character from a string except for a certain list of characters. I'm sure this could be done by storing the list of "allowed" characters in an array then comparing every character in the string with every character in the array (then removing it if it does not find a match). My real question is there an easier way? If someone could point me to the right command or #include I'd really appreciate it.




1
2
3
4
5
6
7
8
9
10
11
12
13
14
// erase everything but a certain list of characters from a string
#include <iostream>
#include <string>

using namespace std;

int main ()
{
string unfiltered ("%h-e(l&l%o$");
//looking for a method to remove everything but "h","e","l","o" from the string

system("PAUSE");
return 0;
}
the easiest way should building a function like this:
1
2
3
4
5
6
7
8
void OnlyLetters(string &st)//pass a string by reference
{
    string temp="";//Create temporary string
    for (unsigned i=0; i< st.length(); i++)//go through each character of the given string
        if ( isalpha( st[i] ) )// if the character is alphabetical ( isalpha is from <cctype> header )
            temp += st[i];// add the character to the temporary string
    st = temp;// set the given string to the resulting value
}
For a general solution, I'd go with

1
2
3
4
5
6
7
8
// remove_matches:  removes all occurrences of all characters 
// in needle from haystack and returns the resulting string.
string remove_matches( string haystack, const string& needle ) {
   // for each character in haystack
   //     if that character is NOT in needle
   //         add it to a new string
   return new_string;
}

Topic archived. No new replies allowed.