Is there any algorithm in c# to singularize - pluralize a word?

前端 未结 11 1841
臣服心动
臣服心动 2020-12-07 10:55

Is there any algorithm in c# to singularize - pluralize a word (in english) or does exist a .net library to do this (may be also in different languages)?

11条回答
  •  旧时难觅i
    2020-12-07 11:27

    As the question was for C#, here is a nice variation on Software Monkey's solution (again a bit of a "cheat", but for me really the most practical and reusable way of doing this):

        public static string Pluralize(this string singularForm, int howMany)
        {
            return singularForm.Pluralize(howMany, singularForm + "s");
        }
    
        public static string Pluralize(this string singularForm, int howMany, string pluralForm)
        {
            return howMany == 1 ? singularForm : pluralForm;
        }
    

    The usage is as follows:

    "Item".Pluralize(1) = "Item"
    "Item".Pluralize(2) = "Items"
    
    "Person".Pluralize(1, "People") = "Person"
    "Person".Pluralize(2, "People") = "People"
    

提交回复
热议问题