Validate String against USPS State Abbreviations

0 votes
I need 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 horribly huge if (or switch) statement to check and compare against all 50 states, but I am asking on this forum since there has to be an easier way of doing this. Is there something out there that I could use to quickly do this the most efficient way possible? like any RegEx or something?
Sep 20, 2018 in IoT (Internet of Things) by Upasana
• 8,590 points
64 views

1 answer to this question.

0 votes

Try something like this:

private static String states = "|AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|";

public static bool isStateAbbreviation (String state)
{
  return state.Length == 2 && states.IndexOf( state ) > 0;
}


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.

answered Sep 20, 2018 by Annie97
• 2,200 points

Related Questions In IoT (Internet of Things)

0 votes
1 answer
0 votes
2 answers

Is there a .NET equivalent to Apache Hadoop?

Hadoop is a Java-based platform. So, to ...READ MORE

answered Jul 15 in Big Data Hadoop by Suhana
• 320 points
221 views
0 votes
1 answer

Authenticate on an ASP.Net Forms Authorization website from a console app

Essentially, we need to record a regular ...READ MORE

answered Sep 20, 2018 in IoT (Internet of Things) by Annie97
• 2,200 points
86 views
0 votes
1 answer

StringBuilder vs. String

To clarify what Gillian said about 4 ...READ MORE

answered Sep 21, 2018 in IoT (Internet of Things) by Upasana
• 8,590 points
95 views
0 votes
1 answer

Validating String against USPS state abbreviations

This is how I'd do it: private static ...READ MORE

answered Nov 9, 2018 in Others by DataKing99
• 8,150 points
326 views
0 votes
1 answer
0 votes
2 answers

Transforming a key/value string into distinct rows in R

We would start off by loading the ...READ MORE

answered Mar 26, 2018 in Data Analytics by Bharani
• 4,560 points
186 views
0 votes
1 answer
+1 vote
2 answers

Should I commit Terraform State files to the git repository?

Its better not to commit it to ...READ MORE

answered Aug 3, 2018 in DevOps & Agile by Nilesh
• 6,970 points
1,063 views