Comparing strings in coldfusion

Best Practices Add comments

This point was taken from the Coldfusion coding guidelines written by Sean Corfield.

Unless you are absolutely CERTAIN that the strings you are comparing will never contain leading zeros, you should ALWAYS do string comparisons using Compare() and / or CompareNoCase().

Not because it's faster than using IS but because it is the only way to truly compare such strings as strings.

If you use IS (or EQ) to compare "001" and "0001" you'll be told that the "strings" are the same. I say "strings" because CF is obviously not comparing strings (else you wouldn't be told those two different strings are the same) --it is obviously comparing numbers. But Compare() and CompareNoCase() always compare actual strings more accurately.

I have also found this interesting link / article on this subject which delves even further into string comparison using CF.

Bookmark and Share

1 response to “Comparing strings in coldfusion”

  1. Charles Robertson Says:
    Nialls. I have never used Compare(), so this might sound like an idiotic question, but does Compare(), compare the string length or the content of the string.
    The reason I ask, is because of the strange return values:

    -1, 0 or 1

    For instance:

    Does Compare("foo","bar") = 0 or -1
    Does Compare("foobar","foo") = 1
    Does Compare("foo","foobar") = -1
    I presume Compare("foo","foo") = 0

    This function kind of confuses because of its ambiguous description in CF Docs.
    "Compared two strings"

    A comparison of what? Length, content or both?

    Thanks for any light you can shed on this matter.

Leave a Reply

Leave this field empty:

Powered by Mango Blog. Design and Icons by N.Design Studio