0

I have tried to search for this topic but I was unable to find any results. My question is: is there any way to figure out the prefix of a word? Whether it is "an" or "a".

For example:

an apple
a house
an old house
an amazon
a vampire

So my input would be just the word and then a function would return the correct prefix.

M J
  • 3
  • 4

2 Answers2

0

Let's assume that any word that begins with a vowel will be preceded by "an" and that all other words will be preceded by "a".

string getArticle(string forWord)
{
  var vowels = new List<char> { 'A', 'E', 'I', 'O', 'U' };

  var firstLetter = forWord[0];
  var firstLetterCapitalized = char.ToUpper(firstLetter);
  var beginsWithVowel = vowels.Contains(firstLetterCapitalized);

  if (beginsWithVowel)
    return "an";

  return "a";
}

Could this be simplified and improved? Of course. However, it should serve as somewhere from which to start.

Less readable but shorter versions exists, such as:

string getArticle(string forWord) => (new List<char> { 'A', 'E', 'I', 'O', 'U' }).Contains(char.ToUpper(forWord[0])) ? "an" : "a";

However, both of these ignore edge cases such as forWord being null or empty.

elmer007
  • 1,412
  • 14
  • 27
0

The links in the comments give the most comprehensive reply but if you were after something very simple to understand the concept, it would be something like this:

To get the indefinite article (prefix) pass the noun:

    public static string prefix(string noun)
    {
        List<string> vowels = new List<string>(){ "A", "E", "I", "O", "U" };
        if (string.IsNullOrWhiteSpace(noun) || noun.Length < 2) return null;
        else return vowels.Contains(noun.Substring(0, 1).ToUpper()) ? "An" : "A";
    }
Jon Roberts
  • 2,262
  • 2
  • 13
  • 17