在c#中有一个简单的方法来创建一个数字的序数吗?例如:
1返回第1位 2返回第2 3返回第3 等
这是否可以通过String.Format()来完成,或者是否有可用的函数来完成?
在c#中有一个简单的方法来创建一个数字的序数吗?例如:
1返回第1位 2返回第2 3返回第3 等
这是否可以通过String.Format()来完成,或者是否有可用的函数来完成?
当前回答
记得国际化!
这里的解决方案只适用于英语。如果您需要支持其他语言,事情就会变得复杂得多。
例如,在西班牙语中,“1st”可以写成“1”。o”、“1。”、“1。o”或“1”。比如“取决于你数的东西是阳性、阴性还是复数!”
因此,如果您的软件需要支持不同的语言,请尽量避免使用序数。
其他回答
我很喜欢Stu和samjudson解决方案中的元素,并将它们结合在一起,形成了我认为可用的组合:
public static string Ordinal(this int number)
{
const string TH = "th";
var s = number.ToString();
number %= 100;
if ((number >= 11) && (number <= 13))
{
return s + TH;
}
switch (number % 10)
{
case 1:
return s + "st";
case 2:
return s + "nd";
case 3:
return s + "rd";
default:
return s + TH;
}
}
这里是DateTime扩展类。复制,粘贴和享受
public static class DateTimeExtensions
{
public static string ToStringWithOrdinal(this DateTime d)
{
var result = "";
bool bReturn = false;
switch (d.Day % 100)
{
case 11:
case 12:
case 13:
result = d.ToString("dd'th' MMMM yyyy");
bReturn = true;
break;
}
if (!bReturn)
{
switch (d.Day % 10)
{
case 1:
result = d.ToString("dd'st' MMMM yyyy");
break;
case 2:
result = d.ToString("dd'nd' MMMM yyyy");
break;
case 3:
result = d.ToString("dd'rd' MMMM yyyy");
break;
default:
result = d.ToString("dd'th' MMMM yyyy");
break;
}
}
if (result.StartsWith("0")) result = result.Substring(1);
return result;
}
}
结果:
2014年10月9日
c# 8和9中接受的带有开关表达式和模式匹配的答案。
没有不必要的字符串转换或分配。
string.Concat(number, number < 0 ? "" : (number % 100) switch
{
11 or 12 or 13 => "th",
int n => (n % 10) switch
{
1 => "st",
2 => "nd",
3 => "rd",
_ => "th",
}
})
或者是不友好的一句话:
$"{number}{(number < 0 ? "" : (number % 100) switch { 11 or 12 or 13 => "th", int n => (n % 10) switch { 1 => "st", 2 => "nd", 3 => "rd", _ => "th" }})}"
简单、干净、快捷
private static string GetOrdinalSuffix(int num)
{
string number = num.ToString();
if (number.EndsWith("11")) return "th";
if (number.EndsWith("12")) return "th";
if (number.EndsWith("13")) return "th";
if (number.EndsWith("1")) return "st";
if (number.EndsWith("2")) return "nd";
if (number.EndsWith("3")) return "rd";
return "th";
}
或者更好的是,作为一个扩展方法
public static class IntegerExtensions
{
public static string DisplayWithSuffix(this int num)
{
string number = num.ToString();
if (number.EndsWith("11")) return number + "th";
if (number.EndsWith("12")) return number + "th";
if (number.EndsWith("13")) return number + "th";
if (number.EndsWith("1")) return number + "st";
if (number.EndsWith("2")) return number + "nd";
if (number.EndsWith("3")) return number + "rd";
return number + "th";
}
}
现在你可以打电话了
int a = 1;
a.DisplayWithSuffix();
甚至直接到
1.DisplayWithSuffix();
我使用这个扩展类:
public static class Int32Extensions
{
public static string ToOrdinal(this int i)
{
return (i + "th")
.Replace("1th", "1st")
.Replace("2th", "2nd")
.Replace("3th", "3rd");
}
}