Concise Way Of Checking Many Conditions

Hi,

Sorry in advance if someone has already asked this question, but I was unable to find anything pertaining to the subject.

I am wanting to check a variable for whether it contains a certain set of characters, but this list of characters is relatively long, and I was wondering if there was a simpler way of writing it out than this:

if((Valid[i] != '0') && (Valid[i] != '1') && ...)

Thanks in advance!
Are the characters in some ASCII ranges or are they arbitrary?

If they are arbitrary, you can create a boolean array:
 
bool isValidChar[256];

Here's the algorithm for avoiding a gazillion comparisons:
1. Use bzero() or memset() to zero out isValidChar[] first: faster than looping through 256 characters.
2. Mark the ones you want valid to be true. For example, if you want 'a' to be valid do this:
 
isValidChar['a'] = true;

Of course, if there are more valid characters than invalid ones, you may want to memset() all of them to true, and set the invalid ones to be false. It's up to you. Of course, the compact way of doing this is to create a string:
 
const char *myValidChars = "adfhklmpqsuvz";

and loop through the string to initialize isValidChar[]. Now you are ready to do your checks.
3. Loop through your string, character by character, indexing into isValidChar[] to see if each character is valid.

Now, you only have to do one comparison, per character, instead of up to 'n' comparisons where 'n' is the number of valid characters. Try writing the code yourself and if you still have questions, post.

If they are not arbitrary, you should look into convenience functions like isalpha() or isnumeric().
Last edited on
1
2
3
4
5
6
7
template <typename T,typename T2>
bool multicomparison(T character,const T2 *characters){
	for (;*characters;characters++)
		if (character==*characters)
			return 1;
	return 0;
}
How about:

1
2
3
4
5
std::string haystack = "hello world!";
static const std::string needles = "!@#$%^&*()";

if( haystack.find_first_of( needles ) != haystack.npos )
    std::cout << "One of the needles was found in the haystack" << std::endl;

Thanks for that guys. Much faster than the way I would have been doing it otherwise! =)
Topic archived. No new replies allowed.