跳過到頁腳內容
.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# 不支援字符串.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 提供對格式化值的對齊和間距的精確控制。 透過在格式項目中加入對齊方式和寬度規格,開發人員可以建立整齊對齊的輸出。 在 C# 中使用 String.Format 控制間距涉及到指定插入字串的寬度,允許精確控制前方或後方的空格。 例如,考慮在銷售報告中對齊產品名稱和價格:

// 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}格式控制"Product"和"Price"標籤的寬度,確保左對齊,並允許前置或後置空格。 然後,迴圈會以產品名稱和價格填入表格,建立格式整齊的銷售報告,並精確控制間距。 調整這些寬度參數可讓您有效管理顯示資料的對齊方式和間距。

使用三元運算符進行條件格式化。

利用 String.Format 中的三元運算符允許根據特定條件進行條件格式化。 舉例來說

// 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 是一個 C# 函式庫,可協助 使用 HTML 建立 PDF 文件從 PDF 檔案擷取文字,以及 PDF 中的修訂與歷史管理。 它為開發人員提供了一套全面的工具,以便在他們的 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 String 表示法建立 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 來建構具有明確格式和占位符的字串,這可以簡化程式碼的可讀性和維護,尤其是在處理複雜的字串操作時。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。