Skip to content

Instantly share code, notes, and snippets.

@jordangray
Last active August 29, 2015 14:15
Show Gist options
  • Save jordangray/bdb3aa1db6f74a625bfe to your computer and use it in GitHub Desktop.
Save jordangray/bdb3aa1db6f74a625bfe to your computer and use it in GitHub Desktop.
A handy utility for pluralising strings based on a numeric value, using standard English pluralisation rules by default.
public static class StringPluralisation
{
private static Regex ConsonantY = new Regex("([bcdfghj-np-tv-z]|qu)y$");
private static Regex Sibilant = new Regex("(s|z|sh|ch)$");
private enum PluralRule { Regular, Sibilant, ConsonantY }
private static PluralRule GetPluralRule(string noun)
{
if (Sibilant.IsMatch(noun)) return PluralRule.Sibilant;
if (ConsonantY.IsMatch(noun)) return PluralRule.ConsonantY;
return PluralRule.Regular;
}
/// <summary>
/// Pluralise a noun, or a phrase ending with a noun, based on the number of items it describes.
/// </summary>
/// <param name="number">The number of items the word describes.</param>
/// <param name="singular">The singular form of the word.</param>
/// <param name="plural">The text to use if there is more than one item. (If not supplied, a plural will be generated based
/// on regular English pluralisation rules.)</param>
/// <param name="zero">The text to use if there is are zero items. (If not supplied and an explicit plural form is provided,
/// that will be used; otherwise, a plural will be generated based on regular English pluralisation rules.)</param>
public static string Pluralise(int number, string singular, string plural = null, string zero = null)
{
if (string.IsNullOrEmpty(singular)) throw new ArgumentNullException("singular");
zero = zero ?? plural;
if (number == 1) return singular;
if (number > 1 && plural != null) return plural;
if (number == 0 && zero != null) return zero ?? plural;
var rule = GetPluralRule(singular.ToLowerInvariant());
var head = singular.Remove(singular.Length - 1);
switch (rule)
{
case PluralRule.ConsonantY : return head + "ies";
case PluralRule.Sibilant : return singular + "es";
default : return singular + "s";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment