How can I correctly prefix a word with "a" and "an"?

Viewed 15431

I have a .NET application where, given a noun, I want it to correctly prefix that word with "a" or "an". How would I do that?

Before you think the answer is to simply check if the first letter is a vowel, consider phrases like:

  • an honest mistake
  • a used car
25 Answers

Rather than writing code that could be culture-dependent and have numerous exceptions I tend to rework the statement that includes the indefinite article. For example, rather than saying "This customer wants to live in a Single-Family Home.", you could say "This customer wants a housing type of 'Single-Family Home'." That way, the indefinite article is not dependent on the variable - e.g., "This customer wants a housing type of 'Apartment'."

I'd like to synthesize a few of the given answers, and contribute my own solutions as well.

Let's start with some basic heuristics:

  1. Start with the first letter of the word.

    • If it starts with an "a", "i" or "o", then use "an". As far as I know, those letters always begin with an actual vowel.
    • If it starts with a "b", "c", "d", "g", "k", "p", "q", "t", "v", "w", or "z", then it is guaranteed to be a consonant, and pronounced like a consonant.
    • If it starts with an "f", "l", "m", "n", "r", "s", or "x", it may be pronounced with a vowel, but only if it's in an acronym. Otherwise, it's guaranteed to be pronounced as a consonant.
    • If it begins with a "u", or with an "h", "j", or "y", then it falls into a corner case.
  2. Determine whether the word is an acronym.

  • If the word is an acronym, then assume that it contains more than one consecutive capital letter, or contains periods. This could be solved via a simple regex (e.g. [A-Z][A-Z]+).
    • If the word is an acronym, then first turn it into a more "word-like" form (i.e., not all capitalized, not containing periods) before going to Step 3. If it isn't an acronym, then refer back to the information in Step 1.
  1. Use a dictionary!
    • If the word is in this dictionary, and begins with an "a", "e", "i", "o", or "u", then it begins with a vowel. Otherwise, it's a consonant.
    • Wiktionary and Wikipedia use the IPA to represent the pronunciations of words. If the word begins with one of these letters, then it begins with a vowel.

Hopefully this helps. I suspect that it will be less resource intensive than any single option, given that much of it can be solved by either a simple "equals" statement (e.g. word[0] == 'a'), or by a regex expression (e.g. [aioAIO]), and by some simple knowledge of linguistics and the pronunciations of the English letter names. If the word doesn't fall into a simple case, then use one of the more complex solutions that the other answerers have provided.

Related