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.
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.