I need to be able to validate a string against a list of the possible United States Postal Service state abbreviations, and Google is not offering me any direction.
I know of the obvious solution: and that is to code a horridly huge if (or switch) statement to check and compare against all 50 states, but I am asking StackOverflow, since there has to be an easier way of doing this. Is there any RegEx or an enumerator object out there that I could use to quickly do this the most efficient way possible?
[C# and .net 3.5 by the way]
I like something like this:
This method has the advantage of using an optimized system routine that is probably using a single machine instruction to do the search. If I was dealing with non-fixed length words, then I’d check for "|" + state + "|" to ensure that I hadn’t hit a substring instead of full match. That would take a wee bit longer, due to the string concatenation, but it would still match in a fixed amount of time. If you want to validate lowercase abbreviations as well as uppercase, then either check for state.UpperCase(), or double the ‘states’ string to include the lowercase variants.
I’ll guarantee that this will beat the Regex or Hashtable lookups every time, no matter how many runs you make, and it will have the least memory usage.