.NET 帮助

C# String.Format(开发人员如何使用)

在 C# 编程的多样性中,有效的字符串操作是显示清晰和动态输出的基石。 String.Format 方法成为一个强大的工具,为开发者提供了一种多样化且富有表现力的字符串格式化方式。 要正确使用String.Format方法并在C#中创建自定义格式字符串,请参考Microsoft官方.NET文档网站上的相关文档:String.Format 方法

在这本综合指南中,我们将探讨字符串格式的复杂性,包括其语法、用法,以及它如何有效提升C#中的字符串格式化。

理解基础知识:

什么是 String.Format?

从根本上说,String.Format 是一种方法,旨在通过用相应的值替换占位符来格式化字符串。 此方法是 C# 中System.String类的一部分,在创建结构良好、可自定义的字符串方面发挥了关键作用。

String.Format 的语法

String Format 方法的语法涉及使用带有占位符的格式项,随后是要替换的值。 这是一个基本的例子:

string formattedString = string.Format("Hello, {0}! Today is {1}.", "John", DateTime.Now.DayOfWeek);
string formattedString = string.Format("Hello, {0}! Today is {1}.", "John", DateTime.Now.DayOfWeek);
Dim formattedString As String = String.Format("Hello, {0}! Today is {1}.", "John", DateTime.Now.DayOfWeek)
$vbLabelText   $csharpLabel

在此示例中,{0}{1} 是占位符,后续的参数(“John” 和 DateTime.Now.DayOfWeek)将在格式化字符串中替换这些占位符。

数字和日期/时间格式化

String.Format 的强大功能之一是能够根据特定模式格式化数字和日期/时间值。 例如

decimal price = 19.95m; 
DateTime currentDate = DateTime.Now;

string formattedNumeric = string.Format("Price: {0:C}", price);
string formattedDate = string.Format("Today's date: {0:yyyy-MM-dd}", currentDate);
decimal price = 19.95m; 
DateTime currentDate = DateTime.Now;

string formattedNumeric = string.Format("Price: {0:C}", price);
string formattedDate = string.Format("Today's date: {0:yyyy-MM-dd}", currentDate);
Dim price As Decimal = 19.95D
Dim currentDate As DateTime = DateTime.Now

Dim formattedNumeric As String = String.Format("Price: {0:C}", price)
Dim formattedDate As String = String.Format("Today's date: {0:yyyy-MM-dd}", currentDate)
$vbLabelText   $csharpLabel

在这个代码片段中,{0:C}将数值格式化为货币,而{0:yyyy-MM-dd}根据指定的模式格式化日期。

带数字索引的多种格式项目

在 C# 中,string.Format 方法允许开发人员在格式字符串中使用数字索引作为占位符。 这有助于按照特定顺序插入相应的值。

string formattedNamed = string.Format("Hello, {0}! Your age is {1}.", "Alice", 30);
string formattedNamed = string.Format("Hello, {0}! Your age is {1}.", "Alice", 30);
Dim formattedNamed As String = String.Format("Hello, {0}! Your age is {1}.", "Alice", 30)
$vbLabelText   $csharpLabel

此处,{0}{1} 是数值占位符,数值按照传递给 string.Format 方法的参数顺序提供。

C# 不支持字符串.Format 方法中的命名占位符,如上图所示的数字索引。 如果需要命名占位符,应使用字符串插值法或外部库提供的其他方法。 下面是一个字符串插值表达式的示例:

字符串插值表达式

字符串插值在 C# 6.0 中引入,允许开发人员直接在字符串字面中使用表达式,使代码更具可读性,并降低了参数重新排序时出错的风险。

var name = "Alice";
var age = 30;
string formattedNamed = $"Hello, {name}! Your age is {age}.";
var name = "Alice";
var age = 30;
string formattedNamed = $"Hello, {name}! Your age is {age}.";
Dim name = "Alice"
Dim age = 30
Dim formattedNamed As String = $"Hello, {name}! Your age is {age}."
$vbLabelText   $csharpLabel

在此示例中,{name}{age} 被直接在字符串中求值,并且这些值由相应的变量提供。

对齐和间距

String.Format 提供了对格式化值的对齐和间距的精确控制。 通过为格式项添加对齐方式和宽度规范,开发人员可以创建对齐整齐的输出。 在C#中使用String.Format来控制空格涉及指定插入字符串的宽度,从而精确地控制前导或后置空格。 例如,考虑对齐销售报告中的产品名称和价格:

string[] products = { "Laptop", "Printer", "Headphones" };
decimal[] prices = { 1200.50m, 349.99m, 99.95m };

Console.WriteLine(String.Format("{0,-15} {1,-10}\n", "Product", "Price"));

for (int index = 0; index < products.Length; index++)
{
    string formattedProduct = String.Format("{0,-15} {1,-10:C}", products[index], prices[index]);
    Console.WriteLine(formattedProduct);
}
string[] products = { "Laptop", "Printer", "Headphones" };
decimal[] prices = { 1200.50m, 349.99m, 99.95m };

Console.WriteLine(String.Format("{0,-15} {1,-10}\n", "Product", "Price"));

for (int index = 0; index < products.Length; index++)
{
    string formattedProduct = String.Format("{0,-15} {1,-10:C}", products[index], prices[index]);
    Console.WriteLine(formattedProduct);
}
Imports Microsoft.VisualBasic

Dim products() As String = { "Laptop", "Printer", "Headphones" }
Dim prices() As Decimal = { 1200.50D, 349.99D, 99.95D }

Console.WriteLine(String.Format("{0,-15} {1,-10}" & vbLf, "Product", "Price"))

For index As Integer = 0 To products.Length - 1
	Dim formattedProduct As String = String.Format("{0,-15} {1,-10:C}", products(index), prices(index))
	Console.WriteLine(formattedProduct)
Next index
$vbLabelText   $csharpLabel

在此示例中,{0,-15}{1,-10}格式控制“Product”和“Price”标签的宽度,确保左对齐并允许前导或尾随空格。 然后,循环将产品名称和价格填充到表格中,创建出格式整齐、间距控制精确的销售报告。 调整这些宽度参数可以有效管理显示数据的对齐方式和间距。

使用三元操作符进行条件格式化

String.Format中利用三元运算符可以根据特定条件进行条件格式化。 例如:

int temperature = 25;
string weatherForecast = string.Format("The weather is {0}.", temperature > 20 ? "warm" : "cool");
int temperature = 25;
string weatherForecast = string.Format("The weather is {0}.", temperature > 20 ? "warm" : "cool");
Dim temperature As Integer = 25
Dim weatherForecast As String = String.Format("The weather is {0}.",If(temperature > 20, "warm", "cool"))
$vbLabelText   $csharpLabel

在这里,天气描述会根据气温的变化而变化。

复合格式

要完善 C# 中对象的显示,可加入格式字符串(也称为 "复合格式字符串")来控制字符串的表示。 例如,使用 {0:d} 表示法将 "d" 格式说明符应用于列表中的第一个对象。在格式化字符串或组合格式功能的上下文中,这些格式说明符指导如何呈现各种类型,包括数字、小数点、日期和时间以及自定义类型。

下面是一个包含单个对象和两个格式项的示例,结合了复合格式字符串和字符串插值法:

string formattedDateTime = $"It is now {DateTime.Now:d} at {DateTime.Now:t}"; Console.WriteLine(formattedDateTime); // Output similar to: 'It is now 4/10/2015 at 10:04 AM'
string formattedDateTime = $"It is now {DateTime.Now:d} at {DateTime.Now:t}"; Console.WriteLine(formattedDateTime); // Output similar to: 'It is now 4/10/2015 at 10:04 AM'
Dim formattedDateTime As String = $"It is now {DateTime.Now:d} at {DateTime.Now:t}"
Console.WriteLine(formattedDateTime) ' Output similar to: 'It is now 4/10/2015 at 10:04 AM'
$vbLabelText   $csharpLabel

在这种方法中,对象的字符串表示可以根据特定格式进行定制,从而使输出更加可控、更具视觉吸引力。 插值字符串直接包含变量,提供了更简洁的语法。

介绍IronPDF

IronPDF 网页

IronPDF 是一个C#库,它方便地通过HTML创建PDF文档从PDF文件中提取文本,以及PDF中的修订和历史管理。 它为开发人员提供了一套全面的工具,用于在其 C# 应用程序中生成、修改和渲染 PDF 文件。 有了 IronPdf,开发人员就可以根据自己的具体要求创建精致且具有视觉吸引力的 PDF 文档。

安装 IronPDF:快速入门

要开始在您的 C# 项目中利用 IronPDF 库,您可以轻松安装 IronPdf NuGet 软件包。 在软件包管理器控制台中使用以下命令:

Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
$vbLabelText   $csharpLabel

或者,您也可以在 NuGet 软件包管理器中搜索 "IronPDF",然后安装。

C# String.Format 的多功能性

C# 的 String.Format 方法因其在制作格式化字符串方面的多功能性而闻名。 它允许开发人员在格式字符串中定义占位符,并用相应的值进行替换,从而提供对字符串输出的精确控制。 能够格式化数值、日期/时间信息,以及对齐文本,使得String.Format成为创建清晰、结构化文本内容的不可或缺的工具。

String.Format 与 IronPDF 的集成

当涉及将String.Format与IronPDF集成时,答案是肯定的。 由String.Format提供的格式化功能可以用于动态生成内容,然后通过 IronPDF 的功能将其合并到 PDF 文档中。

让我们举一个简单的例子:

using IronPdf;

class PdfGenerator
{
    public static void GeneratePdf(string customerName, decimal totalAmount)
    {
        // Format the content dynamically using String.Format
        string formattedContent = string.Format("Thank you, {0}, for your purchase! Your total amount is: {1:C}.", customerName, totalAmount);

        // Create a new PDF document using IronPDF
        var pdfDocument = new ChromePdfRenderer();

        // Add the dynamically formatted content to the PDF
        pdfDocument.RenderHtmlAsPdf(formattedContent).SaveAs("Invoice.pdf");
    }
}

public class Program{
    public static void main(string[] args)
    {
        PdfGenerator obj = new PdfGenerator();
    obj.GeneratePdf("John Doe", "1204.23");
    }
}
using IronPdf;

class PdfGenerator
{
    public static void GeneratePdf(string customerName, decimal totalAmount)
    {
        // Format the content dynamically using String.Format
        string formattedContent = string.Format("Thank you, {0}, for your purchase! Your total amount is: {1:C}.", customerName, totalAmount);

        // Create a new PDF document using IronPDF
        var pdfDocument = new ChromePdfRenderer();

        // Add the dynamically formatted content to the PDF
        pdfDocument.RenderHtmlAsPdf(formattedContent).SaveAs("Invoice.pdf");
    }
}

public class Program{
    public static void main(string[] args)
    {
        PdfGenerator obj = new PdfGenerator();
    obj.GeneratePdf("John Doe", "1204.23");
    }
}
Imports IronPdf

Friend Class PdfGenerator
	Public Shared Sub GeneratePdf(ByVal customerName As String, ByVal totalAmount As Decimal)
		' Format the content dynamically using String.Format
		Dim formattedContent As String = String.Format("Thank you, {0}, for your purchase! Your total amount is: {1:C}.", customerName, totalAmount)

		' Create a new PDF document using IronPDF
		Dim pdfDocument = New ChromePdfRenderer()

		' Add the dynamically formatted content to the PDF
		pdfDocument.RenderHtmlAsPdf(formattedContent).SaveAs("Invoice.pdf")
	End Sub
End Class

Public Class Program
	Public Shared Sub main(ByVal args() As String)
		Dim obj As New PdfGenerator()
	obj.GeneratePdf("John Doe", "1204.23")
	End Sub
End Class
$vbLabelText   $csharpLabel

在此示例中,使用String.Format方法动态生成客户发票的个性化消息。然后使用IronPDF的ChromePdfRenderer功能将格式化的内容合并到PDF文档中。

从前面代码示例输出的PDF

有关使用 HTML 字符串表示创建 PDF 的更多详细信息,请参阅IronPDF 文档页面。

结论

总之,String.Format 在 C# 编程中是一种可靠的工具,为开发者提供了强大的机制来创建格式化字符串。 无论是处理数值、日期/时间信息,还是自定义模式,String.Format 都提供了一个多功能且高效的解决方案。 当您在 C# 开发的广阔领域中导航时,掌握 String.Format 的字符串格式化艺术无疑将提升您在应用程序中创建清晰、动态和视觉吸引力输出的能力。

开发人员可以利用String.Format的强大格式化功能来动态制作内容,然后使用IronPDF将其无缝集成到PDF文档中。 这种合作方式使开发人员能够制作高度定制且具有视觉吸引力的 PDF,为他们的文档生成能力增添了一层复杂性。

IronPDF 提供IronPDF 完整功能的免费试用,可以像在商业模式下一样测试其完整功能。 但是,一旦试用期结束,您将需要IronPDF的许可证

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
C# LINQ 连接查询语法(开发人员如何使用)
下一步 >
C# 特性(开发人员如何使用)