.NET 幫助

C# 字串格式化(開發者使用說明)

發佈 2024年8月11日
分享:

在C#編程的多樣性中,有效的字串操作是顯示清晰和動態輸出的基石。String.Format 方法作為一個強大的工具,提供開發者多用途且表達力強的字串格式化手段。要正確使用 String.Format 方法並在C#中創建自定義格式字串,請參考微軟官方 .NET 文件網站上的相關文檔。 String.Format 方法在本綜合指南中,我們將探討String Format的複雜性、其語法、用法,以及它在C#中提升字串格式化的高效方法。

了解基礎:

What is 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# 不支持像上面數值索引那樣的命名佔位符。如果你需要命名佔位符,你應該使用字符串插值或外部庫提供的其他方法。以下是字符串插值表達式的示例:

字串插值表達式

在 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 提供對格式化值的對齊和間距進行精確控制。通過向格式項目中添加對齊和寬度規範,開發人員可以創建整齊對齊的輸出。使用 String.Format 控制 C# 中的間距涉及到指定插入字符串的寬度,從而能夠精確控制前導或後尾空格。例如,考慮在銷售報告中對齊產品名稱和價格:

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 成為創建清晰且結構化文本內容的不可或缺的工具。

與 IronPDF 整合 String.Format

當涉及到將 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的更詳細信息,請參閱 文檔 頁面。

結論

總而言之,String.Format 是 C# 編程中的一個中流砥柱,為開發者提供了一個穩健的機制來製作格式化字符串。無論是處理數值、日期/時間信息,還是自定義模式,String.Format 都提供了一個多功能且高效的解決方案。在您導航 C# 開發的廣闊領域時,掌握使用 String.Format 進行字符串格式化的藝術,無疑會增強您在應用程序中創建清晰、動態和視覺上吸引人的輸出的能力。

開發者可以利用 String.Format 強大的格式化功能來動態製作內容,然後使用 IronPDF 無縫地集成到 PDF 文件中。這種協作方法使開發者能夠生成高度自定義和視覺吸引人的 PDF,為其文檔生成能力增添了一層精緻。

IronPDF 提供一 免費試用 要像在商業模式中一樣測試其完整功能。不過,您需要一個 授權 試用期結束後。

< 上一頁
C# LINQ Join 查詢語法(對開發者的工作原理)
下一個 >
C# 屬性(開發人員如何運作)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >