.NET 幫助

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

在多樣化的 C# 程式設計中,有效的字符串操作是顯示清晰且動態輸出的基石。 String.Format 方法是一個強大的工具,為開發人員提供了一種靈活且具有表達力的字串格式化方式。 要在C#中正確使用String.Format方法並創建自定義格式字串,請參閱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# 不支援像上面顯示的數字索引那樣在 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}."
$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 Join 查詢語法(對開發者的工作原理)
下一個 >
C# 屬性(開發人員如何運作)