.NET 帮助

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

发布 2024年八月11日
分享:

在多样化的C#编程中,有效的字符串操作是显示清晰和动态输出的基石。String.Format方法作为一个强大的工具,为开发者提供了一种多功能且富有表现力的字符串格式化手段。要正确使用String.Format方法并在C#中创建自定义格式字符串,请参考微软官方 .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)
VB   C#

在本例中,{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)
VB   C#

在这个片段中,{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)
VB   C#

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

C# 不支持在 string.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}."
VB   C#

在本例中,{名字}{年龄} 在字符串内直接进行评估,值由相应的变量提供。

对齐和间距

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
VB   C#

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

结合条件运算符进行条件格式化

利用 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"))
VB   C#

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

复合格式化

要在 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'
VB   C#

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

IronPDF 简介

IronPDF 网页

IronPDF 是一个 C# 库,可帮助 创建, 阅读操控 的 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
VB   C#

或者,您也可以在 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
VB   C#

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

上一个代码示例输出的 PDF

有关使用 HTML 字符串表示法创建 PDF 的详细信息,请参阅 文件 page.

结论

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

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

IronPDF 提供了一种 免费试用 测试其全部功能,就像在商业模式下一样。不过,您需要一个 许可证 一旦超过试用期。

< 前一页
C# LINQ 连接查询语法(开发人员如何使用)
下一步 >
C# 属性(开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >