Using C# to get the plural noun

06 Feb

Getting a plural noun for a given string seems to be easy, but I failed to find a C# class to do so. There are several rules which goven how the plural form of a word should be generated, for instance:

  • Nouns ending in s, z, x, sh, and ch form the plural by adding – es
  • Nouns ending in – y preceded by a consonant is formed into a plural by changing – y to – ies.
  • Nouns ending in y preceded by a vowel form their plurals by adding – s. (e.g. boy, boys; day, days)
  • Most nouns ending in o preceded by a consonant is formed into a plural by adding es
  • Some nouns ending in f or fe are made plural by changing f or fe to – ves. (e.g. beef, beeves; wife, wives)

See more detailed rules here.

So to provide a c# implementation, we can user Regular Expression to accomplish this. For instance, to detect the words ending in s, z, x, sh, and ch, we can use the following code:

Regex g = new Regex(@”s\b|z\b|x\b|sh\b|ch\b”);
MatchCollection matches = g.Matches(NounString);
if (matches.Count > 0)
NounString += “es”;

Here the “s\b” refers to the words ending with “s” (if we want to get the words starting with “p”, we can use “\bp”, the “\b” indicates Boundary.) and “|” is the logic OR relation.

Similarly, to get nouns ending in – y preceded by a consonant, use the code:

if (NounString.EndsWith(“y”, true, CultureInfo.InvariantCulture))
Regex g2 = new Regex(@”(ay|ey|iy|oy|uy)\b”);
if (g2.Matches(NounString).Count <= 0) //e.g. cities
NounString = NounString.Substring(0, NounString.Length – 1) + “ies”;
NounString += “s”;

Simple, isn’t it?

Other than getting the plural forms using such rules, there are some exceptions, and this is implemented using lookup tables. And if words are in the table, simply output these irregular forms:

for(int i=0;i<ExceptionWords_IrregularInput.Length;i++)
if (string.Compare(ExceptionWords_IrregularInput[i], NounString, true, CultureInfo.InvariantCulture) == 0)
return ExceptionWords_IrregularOutput[i];

That is it. Download the source file here. Note that p rior permissions must be obtained for commercial usage.

About these ads
Leave a comment

Posted by on February 6, 2009 in Dotnet/C#


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

Join 50 other followers

%d bloggers like this: