Question

I am working on a personal C++ project and one of the features is to save contact information. When it comes to the address I want the state to save in its abbreviation format.

I am working on a method that will accept a string input of the full name of the state and return a string value of the 2 character state abbreviation. That being said I have been brainstorming with some friends as to the best way to do this. As of right now I have finished the states that begin with 'A'; but before I go through the other 47 states I wanted to broaden my brainstorming by asking this question. If there a "better" or more efficient way to accomplish this? Please look at my function so far.

    std::string Address::formatStateInput(std::string stateInput){
        char firstLetter = toupper(stateInput.at(0)); //makes first character capital for easy checking
        if(firstLetter == 'A'){
        char letterToCheck = toupper(stateInput.at(3)); //makes fourth character capital for easy checking
            //Alabama
            if (letterToCheck == 'B'){
                return "AL";    
            }
            //Alaska
            else if (letterToCheck == 'S'){
                return "AK";
            }
            //Arizona
            else if (letterToCheck == 'Z'){
                return "AZ";
            }
            else{
                return "NULL";
            }
        }
        else{return "NULL";}
    }
Was it helpful?

Solution

I would use an std::map (or std::unordered_map).

std::map<std::string, std::string> abbrs;

abbrs["Alabama"] = "AL";
abbrs["Alaska"] = "AK";
abbrs["Arizona"] = "AZ";
// ...

Then to look up a state's abbreviation, you'd do something like:

auto pos = abbrs.find(user_input_state_name);
if (pos == abbrs.end())
    error_invalid_state_name(user_input_state_name);
else
    abbreviation = *pos;

Note that in a typical case, you probably don't want to really hard-code all the state names and abbreviations into your source code. You probably want to have the names and abbreviations in an external configuration file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top