跳過到頁腳內容
.NET幫助

C# String.Format(對於開發者的運行原理)

在 C# 程式設計的多樣性中,有效的字串操作是顯示清晰動態輸出的基石。 String.Format 方法是一個強大的工具,為開發人員提供了一種多用途且具表達性的方式來格式化字串。 要正確使用 String.Format 方法並在 C# 中建立自訂格式字串,請參閱 Microsoft 官方 .NET 文件網站上的文檔:String.Format 方法

在這篇全面的指南中,我們將探索 String Format 的複雜性、其語法、用法以及它提高 C# 中字串格式化的有效方法。

理解基本概念:

什麼是 String.Format?

在其核心中,String.Format 方法被設計用來通過替換占位符為相應值來格式化字串。 此方法是 C# 中 System.String 類的一部分,對於創建結構良好、可自訂字串起著關鍵作用。

String.Format 的語法

String Format 方法的語法包括使用具有占位符的格式項,隨後是要替換的值。 這是一個基本範例:

// String.Format example demonstrating basic placeholder usage
string formattedString = string.Format("Hello, {0}! Today is {1}.", "John", DateTime.Now.DayOfWeek);
// String.Format example demonstrating basic placeholder usage
string formattedString = string.Format("Hello, {0}! Today is {1}.", "John", DateTime.Now.DayOfWeek);
' String.Format example demonstrating basic placeholder usage
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 的一個強大功能是根據特定模式格式化數字和日期/時間值。 例如:

// Formatting numeric and date/time values
decimal price = 19.95m; 
DateTime currentDate = DateTime.Now;

string formattedNumeric = string.Format("Price: {0:C}", price); // Formats the numeric value as currency
string formattedDate = string.Format("Today's date: {0:yyyy-MM-dd}", currentDate); // Formats the date
// Formatting numeric and date/time values
decimal price = 19.95m; 
DateTime currentDate = DateTime.Now;

string formattedNumeric = string.Format("Price: {0:C}", price); // Formats the numeric value as currency
string formattedDate = string.Format("Today's date: {0:yyyy-MM-dd}", currentDate); // Formats the date
' Formatting numeric and date/time values
Dim price As Decimal = 19.95D
Dim currentDate As DateTime = DateTime.Now

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

在此片段中,{0:C} 將數值格式化為貨幣,而 {0:yyyy-MM-dd} 則根據指定的模式格式化日期。

具有數字索引的多重格式項

在 C# 中,string.Format 方法允許開發人員在格式字串中使用數字索引作為佔位符。 這有助於按照特定順序插入相應的值。

// Demonstrating multiple format items with numerical indices
string formattedNamed = string.Format("Hello, {0}! Your age is {1}.", "Alice", 30);
// Demonstrating multiple format items with numerical indices
string formattedNamed = string.Format("Hello, {0}! Your age is {1}.", "Alice", 30);
' Demonstrating multiple format items with numerical indices
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 引入了字串插值,允許開發人員在字串文字中直接使用表達式,這使得代碼更具可讀性並減少在重新排序參數時出錯的風險。

// String interpolation example demonstrating direct variable use
var name = "Alice";
var age = 30;
string formattedNamed = $"Hello, {name}! Your age is {age}.";
// String interpolation example demonstrating direct variable use
var name = "Alice";
var age = 30;
string formattedNamed = $"Hello, {name}! Your age is {age}.";
' String interpolation example demonstrating direct variable use
Dim name = "Alice"
Dim age = 30
Dim formattedNamed As String = $"Hello, {name}! Your age is {age}."
$vbLabelText   $csharpLabel

在此範例中,{name}{age} 被直接在字串中評估,這些值由相應的變數提供。

對齊與間距

String.Format 提供精確控制格式化值的對齊和間距。 通過為格式項添加對齊和寬度規範,開發者可以創建整齊對齊的輸出。 使用 String.Format 控制 C# 中的間距涉及指定插入字串的寬度,允許對前導或後續空格進行精確控制。 舉例來說,考慮在銷售報告中對齊產品名稱和價格:

// Using String.Format for aligning product names and prices
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);
}
// Using String.Format for aligning product names and prices
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

' Using String.Format for aligning product names and prices
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} 格式控制了“產品”和“價格”標籤的寬度,確保左對齊並允許前導或後續空格。 然後循環填充產品名稱和價格的表格,創建一個間隔精確控制的整齊格式的銷售報告。 調整這些寬度參數允許您有效地管理顯示數據的對齊和空白。

具有三元運算符的條件格式化

利用 String.Format 中的三元運算符,可以根據特定標準進行條件格式化。 PDF 的創建和生成由 iText 7 支持,而 HTML 到 PDF 的轉換由 pdfHTML 支持。

// Using ternary operator for conditional formatting
int temperature = 25;
string weatherForecast = string.Format("The weather is {0}.", temperature > 20 ? "warm" : "cool");
// Using ternary operator for conditional formatting
int temperature = 25;
string weatherForecast = string.Format("The weather is {0}.", temperature > 20 ? "warm" : "cool");
' Using ternary operator for conditional formatting
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”格式說明符。在格式化字符串的上下文或複合格式化功能中,這些格式說明符指導各種型別的格顯示,包括數字、小數點、日期和時間以及自訂類型。

這裡有一個單一物件和兩個格式項的範例,結合了複合格式字符串和字符串插值:

// Combining composite format strings and string interpolation
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'
// Combining composite format strings and string interpolation
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'
' Combining composite format strings and string interpolation
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 is a C# library that facilitates the creation of PDF documents using HTML, extracting text from PDF files, and revision and history management in PDFs. 它為開發人員提供了一組全面的工具,用於在 C# 應用程式中生成、修改和呈現 PDF 文件。 通過 IronPDF,開發人員可以創建符合其特定需求的精美且引人注目的 PDF 文件。

安裝IronPDF:快速入門

要在您的 C# 專案中開始使用 IronPDF 庫,您可以輕鬆安裝 IronPdf NuGet 套件。 在您的包管理器控制台中使用以下命令:

# Install the IronPdf NuGet package
Install-Package IronPdf
# Install the IronPdf NuGet package
Install-Package IronPdf
SHELL

或者,您可以在NuGet程序包管理器中搜索"IronPDF"並從那裡安裝。

C# String.Format 的多樣性

C# 的 String.Format 方法以其在構建格式化字串方面的多樣性而聞名。 它允許開發人員在格式字串中定義佔位符並用相應的值替代這些佔位符,提供對字串輸出的精確控制。 格式化數值、日期/時間資訊以及對齊文本的能力,使得 String.Format 成為創建清晰且結構化文本內容的不可或缺的工具。

String.Format 與 IronPDF 的整合

當談到 String.Format 與 IronPDF 的整合時,答案是肯定的。 String.Format 提供的格式化功能可以用來動態生成內容,該內容然後使用 IronPDF 的功能納入 PDF 文檔中。

讓我們考慮一個簡單的例子:

using IronPdf;

// Class to generate PDF with formatted content
class PdfGenerator
{
    // Method to generate a PDF for a customer's invoice
    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 and save it
        pdfDocument.RenderHtmlAsPdf(formattedContent).SaveAs("Invoice.pdf");
    }
}

public class Program
{
    // Main method to execute PDF generation
    public static void Main(string[] args)
    {
        PdfGenerator.GeneratePdf("John Doe", 1204.23m);
    }
}
using IronPdf;

// Class to generate PDF with formatted content
class PdfGenerator
{
    // Method to generate a PDF for a customer's invoice
    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 and save it
        pdfDocument.RenderHtmlAsPdf(formattedContent).SaveAs("Invoice.pdf");
    }
}

public class Program
{
    // Main method to execute PDF generation
    public static void Main(string[] args)
    {
        PdfGenerator.GeneratePdf("John Doe", 1204.23m);
    }
}
Imports IronPdf

' Class to generate PDF with formatted content
Friend Class PdfGenerator
	' Method to generate a PDF for a customer's invoice
	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 and save it
		pdfDocument.RenderHtmlAsPdf(formattedContent).SaveAs("Invoice.pdf")
	End Sub
End Class

Public Class Program
	' Main method to execute PDF generation
	Public Shared Sub Main(ByVal args() As String)
		PdfGenerator.GeneratePdf("John Doe", 1204.23D)
	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 的許可證

常見問題解答

如何使用 String.Format 在 C# 中生成 PDF?

String.Format 可以用來創建格式化內容,然後使用 IronPDF 的 ChromePdfRenderer 渲染含有格式化字串的 HTML 將其納入 PDF 檔中。

使用 String.Format 進行數字和日期/時間格式化的好處是什麼?

String.Format 允許開發者為數字和日期/時間值定義特定模式,例如貨幣或日期顯示,這有助於創建結構化且易於閱讀的輸出。

字串插值如何增強 C# 中的字串格式化?

引入於 C# 6.0 的字串插值允許開發者直接在字串字面中插入表達式,從而提高可讀性並減少錯誤,這在格式化動態內容時特別有用。

String.Format 如何協助格式化字串中的對齊和間距?

String.Format 通過在格式項中指定寬度來控制對齊和間距,使開發人員能夠生成整齊對齊的輸出,例如報告或表格。

String.Format 可以處理條件格式化嗎?

是的,String.Format 可以包含三元運算符以進行條件格式化,這使根據條件動態變更字串內容成為可能,例如根據變數值改變文字。

在 C# 的背景下,什麼是複合格式化?

C# 中的複合格式化使用格式字串來控制對象如何表示為字串,允許使用格式規範符處理各種數據類型以保證一致且格式化的輸出。

如何利用 IronPDF 與 String.Format 進行文檔生成?

IronPDF 可以使用 String.Format 準備動態內容,然後轉換成視覺上吸引人的 PDF,增強 C# 應用中文檔生成的能力。

在 String.Format 中數字索引的重要性是什麼?

String.Format 中的數字索引是占位符,用於指示格式字串中值的插入順序,提供了一種管理復雜字串結構的有效方法。

為何 String.Format 被認為在 C# 開發中具有多功能性?

String.Format 在於其能夠精確控制各種數據類型和模式來格式化字串,使其在創建清晰、動態且結構化的輸出時必不可少。

開發者如何利用 String.Format 改善其代碼的可讀性?

開發者可以使用 String.Format 構建具有清晰格式和占位符的字串,簡化代碼的可讀性和維護性,特別是在處理複雜字串操作時。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。