Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - fastest way to compare two strings using wildcards

Is there a fastest way to compare two strings (using the space for a wildcard) than this function?

public static bool CustomCompare(this string word, string mask)
{

    for (int index = 0; index < mask.Length; index++)
    {
        if (mask[index] != ' ') && (mask[index]!= word[index]))
        {
            return false;
        }
    }
    return true;
}

Example: "S nt nce" comparing with "Sentence" will return true. (The two being compared would need to be the same length)

like image 330
Gregoire Avatar asked Dec 30 '22 02:12

Gregoire


2 Answers

If mask.length is less than word.length, this function will stop comparing at the end of mask. A word/mask length compare in the beginning would prevent that, also it would quick-eliminate some obvious mismatches.

like image 164
Rob Elliott Avatar answered Jan 30 '23 20:01

Rob Elliott


The loop is pretty simple and I'm not sure you can do much better. You might be able to micro optimize the order of the expression in the if statement. For example due to short circuiting of the && it might be faster to order the if statement this way

 if (mask[index]!= word[index])) && (mask[index] != ' ')

Assuming that matching characters is more common that matching the wildcard. Of course this is just theory I wouldn't believe it made a difference without benchmarking it.

And as others have pointed out the routine fails if the mask and string are not the same length.

like image 35
Kevin Gale Avatar answered Jan 30 '23 22:01

Kevin Gale