Pluralizes the specified string if needed, i.e. if the specified count is not equal to 1. - CSharp System

CSharp examples for System:String Search

Description

Pluralizes the specified string if needed, i.e. if the specified count is not equal to 1.

Demo Code


using System.Globalization;
using System;/*from w  w w.  j a va 2 s.  c  o  m*/

public class Main{
        #endregion

        #region Pluralize

        /// <summary>
        /// Pluralizes the specified string if needed, i.e. if the specified count is not equal to 1.
        /// </summary>
        /// <param name="singular">The singular version of the string.</param>
        /// <param name="count">The number of items.</param>
        /// <returns>The singular version of the string if count is equal to 1, the plural version otherwise.</returns>
        public static string Pluralize(this string singular, int count)
        {
            if (singular == null)
            {
                throw new ArgumentNullException("singular");
            }
            if (count < 0)
            {
                throw new ArgumentException("The count cannot be negative.");
            }
            if (count == 1)
            {
                return singular;
            }
            else
            {
                if (singular.EndsWith("y", StringComparison.OrdinalIgnoreCase))
                {
                    return singular.Substring(0, singular.Length - 1) + "ies";
                }
                else if (singular.EndsWith("ch", StringComparison.OrdinalIgnoreCase))
                {
                    return singular + "es";
                }
                else
                {
                    return singular + "s";
                }
            }
        }
}

Related Tutorials