c# - 如何格式化包含数字和字符的字符串

标签 c# string-formatting

我有以下字符串 "2017-2",我需要将其格式化为 "2017-02"

var period = "2017-2";
var periodFormatted = String.Format("{0:0000-00}", period);  

periodFormatted 返回 "2017-2"

将句点格式化为 "2017-02" 的正确语法是什么?

最佳答案

string.Format 不会知道(或关心)您的字符串包含数字,因此您不能像那样直接格式化。您可以拆分字符串并将最后一部分解析为数字。例如:

var period = "2017-2";
var parts = period.Split('-');;
var periodFormatted = $"{parts[0]}-{int.Parse(parts[1]):D2}";

但是,您应该首先将 period 值作为适当的 DateTime 对象(或表示年月值的自定义类型),这样使格式变得微不足道。

关于c# - 如何格式化包含数字和字符的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47697195/

相关文章:

python - 结合固定和区域设置表示法进行字符串格式化

c# - 从 Active Directory 组获取用户

c# - 如何从字符串中删除 DateTime 子字符串

c# - 嵌套 GridView - 如何触发子 GridView 按钮单击事件

c# - 流利的断言 : Assert one OR another value

c# - Format Decimal 2 Places - 无尾随零

c# - 如何将毫秒转换为显示mm :ss in XAML?

android - 使用 Html.fromHtml 设置自定义字体

c# - 用Mars更新7000行效率高吗?

c# - 具有通用基类的ASP.NET Core 2.0存储库模式