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>
usingnamespace 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
}
// 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;
}