Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate String against USPS State Abbreviations

Tags:

c#

.net

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]

List of USPS State Abbreviations

like image 437
Matthew Ruston Avatar asked Oct 06 '08 20:10

Matthew Ruston


People also ask

Does the post office prefer state abbreviations?

Abbreviate U.S. states, Washington D.C. and U.S. territories with the USPS-approved 2-letter postal codes. Avoid confusing the USPS-approved abbreviations with other state abbreviations like WASH instead of WA. Also, remember two spaces are preferred between the state and ZIP Code.

Can you abbreviate States on mail?

To allow space for the ZIP Code in the last line of an address, state names needed to be abbreviated. Previously, the Post Office Department preferred that state names be written in full, to avoid confusion.


1 Answers

A HashSet<string> is the cleanest way I can think of using the built-in types in .NET 3.5. (You could easily make it case-insensitive as well, or change it into a Dictionary<string, string> where the value is the full name. That would also be the most appropriate solution for .NET 2.0/3.0.)

As for speed - do you really believe this will be a bottleneck in your code? A HashSet is likely to perform "pretty well" (many millions of lookups a second). I'm sure alternatives would be even faster - but dirtier. I'd stick to the simplest thing that works until you have reason to believe it'll be a bottleneck.

(Edited to explicitly mention Dictionary<,>.)

like image 115
Jon Skeet Avatar answered Oct 14 '22 09:10

Jon Skeet