States and their abbreviations are among my favorite kinds of data - they almost never ever change and, as such, you can hard code all that information into your app. I mean, why bother fetching it from the database every page load? That's just wasted CPU cycles.

So, I can find merit in the hard-coded approach that the below code takes that Alex E. sent our way. However, I definitely believe that it takes guts for anybody to make a claim about the efficiency of strcmp() when you perform a linear search on an ordered list.

const char *StAbbrs[] = {".", "AA", "AB", "AE", "AK", "AL", "AP", "AR",
"AS", "AZ", "BC", "CA", "CI", "CO", "CT", "CZ", "DC", "DE", "FL", "GA",
"GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MB", "MD",
"ME", "MI", "MN", "MO", "MP", "MS", "MT", "NB", "NC", "ND", "NE", "NF",
"NH", "NJ", "NM", "NS", "NV", "NY", "OH", "OK", "ON", "OR", "PA", "PE",
"QC", "PR", "RI", "SC", "SD", "SK", "TN", "TX", "US", "UT", "VA", "VI",
 "VT", "WA", "WI", "WV", "WY"};

const char *StateNames[] = {"Foreign Address", "Americas", "Alberta",
 "Europe", "Alaska", "Alabama", "Pacific", "Arkansas", "American Samoa",
 "Arizona", "British Columbia", "California", "Cayman Islands",
 "Colorado", "Connecticut", "Canal Zone", "Dist. of Columbia",
 "Delaware", "Florida", "Georgia", "Guam", "Hawaii", "Iowa", "Idaho",
 "Illinois", "Indiana", "Kansas", "Kentucky", "Louisiana", 
 "Massachusetts", "Manitoba", "Maryland", "Maine", "Michigan",
 "Minnesota", "Missouri", "Mariana Island", "Mississippi", "Montana", 
 "New Brunswick", "North Carolina", "North Dakota", "Nebraska", "Newfoundland", "New Hampshire", "New Jersey", "New Mexico", 
 "Nova Scotia", "Nevada", "New York", "Ohio", "Oklahoma", "Ontario", 
 "Oregon", "Pennsylvania", "Prince Edward Is.", "Quebec", "Puerto Rico", 
 "Rhode Island", "South Carolina", "South Dakota", "Saskatchewan", 
 "Tennessee", "Texas", "Federal", "Utah", "Virginia", "Virgin Islands", 
 "Vermont", "Washington", "Wisconsin", "West Virginia", "Wyoming"};

const char *StateName(const char *StAbbr) {
  for(short index = 0; index < MaxNumStates; index++)
  {		
    // It is faster to compare the two character strings 
    // as shorts than do a strcmp() on them.

    if(*(short *)StAbbr == *(short *)(StAbbrs[index]))
      return StateNames[index];

  }
  return "";
}
[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!