Java有没有一种简单的复数方法?如果没有,我想知道为什么当Rails有一个时,它是不可用的。
有什么特别的原因吗?
发布于 2013-04-25 02:53:16
jtahlborn在语言特异性方面有一个很好的观点。也就是说,这是我为在我们的应用程序中使用而编写的代码。它并不全面,但是当你遇到异常时,添加它们是很容易的。
这是C#,但应该足够接近,或者您可以适应:
public string GetPlural(string singular)
{
string CONSONANTS = "bcdfghjklmnpqrstvwxz";
switch (singular)
{
case "Person":
return "People";
case "Trash":
return "Trash";
case "Life":
return "Lives";
case "Man":
return "Men";
case "Woman":
return "Women";
case "Child":
return "Children";
case "Foot":
return "Feet";
case "Tooth":
return "Teeth";
case "Dozen":
return "Dozen";
case "Hundred":
return "Hundred";
case "Thousand":
return "Thousand";
case "Million":
return "Million";
case "Datum":
return "Data";
case "Criterion":
return "Criteria";
case "Analysis":
return "Analyses";
case "Fungus":
return "Fungi";
case "Index":
return "Indices";
case "Matrix":
return "Matrices";
case "Settings":
return "Settings";
case "UserSettings":
return "UserSettings";
default:
// Handle ending with "o" (if preceeded by a consonant, end with -es, otherwise -s: Potatoes and Radios)
if (singular.EndsWith("o") && CONSONANTS.Contains(singular[singular.Length - 2].ToString()))
{
return singular + "es";
}
// Handle ending with "y" (if preceeded by a consonant, end with -ies, otherwise -s: Companies and Trays)
if (singular.EndsWith("y") && CONSONANTS.Contains(singular[singular.Length - 2].ToString()))
{
return singular.Substring(0, singular.Length - 1) + "ies";
}
// Ends with a whistling sound: boxes, buzzes, churches, passes
if (singular.EndsWith("s") || singular.EndsWith("sh") || singular.EndsWith("ch") || singular.EndsWith("x") || singular.EndsWith("z"))
{
return singular + "es";
}
return singular + "s";
}
}一个额外的用法说明...正如您可能看到的,它希望您传入的任何单词的第一个字母都是大写的(如果它不在异常列表中,这并不重要)。有无数不同的方法来处理这个问题。它只是满足了我们的特殊需求。
发布于 2020-07-22 23:59:48
看看JBoss's Inflector class吧。即使您没有使用JBoss,您也可以在源代码中找到一种全面的方法来实现这一点。
https://stackoverflow.com/questions/16199833
复制相似问题