Plurality in user messages

前端 未结 25 1515
没有蜡笔的小新
没有蜡笔的小新 2021-01-30 01:53

Many times, when generating messages to show to the user, the message will contain a number of something that I want to inform the customer about.

I\'ll give a

25条回答
  •  走了就别回头了
    2021-01-30 02:43

    My general approach is to write a "single/plural function", like this:

    public static string noun(int n, string single, string plural)
    {
      if (n==1)
        return single;
      else
        return plural;
    }
    

    Then in the body of the message I call this function:

    string message="Congratulations! You have won "+n+" "+noun(n, "foobar", "foobars")+"!";
    

    This isn't a whole lot better, but at least it, (a) puts the decision in a function and so unclutters the code a little, and (b) is flexible enough to handle irregular plurals. i.e. it's easy enough to say noun(n, "child", "children") and the like.

    Of course this only works for English, but the concept is readily extensible to languages with more complex endings.

    It occurs to me that you could make the last parameter optional for the easy case:

    public static string noun(int n, string single, string plural=null)
    {
      if (n==1)
        return single;
      else if (plural==null)
        return single+"s";
      else
        return plural;
    }
    

提交回复
热议问题