IRONSOFTWAREHOME
開發者更新

C# Substring(對於開發者的運行原理)

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: 2026年4月23日

在 C# 中,Substring 方法 是操作字串時的重要工具。 此功能允許開發人員根據指定的字元位置提取字串的一部分。 本指南旨在深入解析公共字串 Substring 方法和 IronPDF 程式庫,提供詳細的範例和解釋,以便初學者全面了解其使用和功能。

理解 Substring 方法

C# 的 Substring 方法是 String 類別的成員,允許從指定參數的第一個字元開始進行操作。 它用於從指定索引開始檢索字串的一部分,並可選擇指定長度。 此方法的語法簡單,易於在需要字串操作的任何編碼情況下實施。

語法和參數

Substring 方法有兩種主要形式:

public string Substring(int startIndex);
public string Substring(int startIndex, int length);
  1. public string Substring(int startIndex): 這會檢索從 startIndex 開始到字串結尾的子字串。
  2. public string Substring(int startIndex, int length): 這會檢索從 startIndex 開始且指定 length 的子字串。

相關參數包括:

  • int startIndex: 這是子字串開始的零基索引。
  • int length: (可選)這是第二個參數。 這是所返回子字串中要包含的字元數。

Substring 方法的工作原理

Substring 方法的過程很簡單。 當被調用時,它從原始字串的給定索引處(startIndex)提取字元。 如果提供了 length 參數,該方法會返回指定數量的字元。 在沒有提供 length 參數時,會繼續到字串結尾。 在 C# 中使用 Substring 確保兩個參數(startIndex 和 length)作為整數處理,強制型別安全,並防止潛在的運行時錯誤。

Substring 方法的詳細範例

為了更好地理解 Substring 方法的實現,讓我們看幾個說明其實際應用的例子。

提取到字串結尾

假設您有一個字串,並且需要從特定索引提取一個子字串到字串結尾。 以下是您可能的做法:

// Main method demonstrating substring extraction
public static void Main(string[] args)
{
    string text = "Hello, world!";
    string substring = text.Substring(7); // Extract from index 7 to the end
    Console.WriteLine(substring);
}
C#

輸出:

world!
Text

在這個例子中,Substring 方法從索引 7 開始,這對應於"世界!"中的 'w',並檢索到字串結尾的每個字元。 當子字串的長度是動態的或未預先確定時,這特別有用。

提取具有指定長度的子字串

現在,讓我們看看一個情況,其中子字串的開始索引和長度都已指定:

// Main method demonstrating substring extraction with specified length
public static void Main(string[] args)
{
    string text = "Hello, world!";
    string substring = text.Substring(7, 5); // Starts at index 7, length of 5
    Console.WriteLine(substring);
}
C#

輸出:

world
Text

這裡,子字串從第七個字元開始,跨越五個字元長。 當您需要精確控制子字串的邊界時,此方法非常有用。

從字串陣列中檢索子字串

假設您有一個字串陣列,並希望根據指定的字元位置和長度從每個字串中提取子字串。 您可以使用 foreach 迴圈來遍歷陣列,並將 Substring 方法應用於每個字串。

// Example of extracting substrings from an array of strings
string[] array = { "apple", "banana", "orange" };
foreach (string str in array)
{
    string substring = str.Substring(1, 3); // Substring starts from index 1
    Console.WriteLine(substring);
}

這段程式碼將輸出:

ppl
ana
ran
Text

處理邊緣情況

考慮邊緣情況以避免運行時錯誤,如 ArgumentOutOfRangeException,是很重要的。 在使用 Substring 方法時,必須確保指定的字元位置和長度在原始字串的範圍內。 否則,可能會導致索引超出範圍的例外。 您可以檢查原始字串的長度,以避免此類異常。 以下是一些要點:

  • startIndex 必須在字串的範圍內。
  • startIndexlength 的總和不得超過原始字串的長度。
  • 不允許 startIndexlength 的負值,並且會導致錯誤。

檢查索引的有效性

為確保您的子字串提取不會引發錯誤,您可以新增檢查:

// Main method with checks to avoid ArgumentOutOfRangeException
public static void Main(string[] args)
{
    string text = "Hello, world!";
    int startIndex = 7;
    int length = 5;
    if (startIndex >= 0 && startIndex < text.Length && startIndex + length <= text.Length)
    {
        string substring = text.Substring(startIndex, length);
        Console.WriteLine(substring);
    }
    else
    {
        Console.WriteLine("Invalid substring parameters.");
    }
}
C#

此程式碼塊確保在嘗試提取子字串之前,子字串參數有效,從而避免潛在的運行時錯誤。

在 C# 中整合 IronPDF 和 Substring 用於動態 PDF 建立

IronPDF 是一個強大的 PDF 程式庫,允許開發人員直接在 .NET 應用程式中建立、操作和呈現 PDF 文件。 它允許 HTML 轉 PDF,以幫助建立自訂和美觀的 PDF 文件。 IronPDF 支援一系列 PDF 操作,包括從 HTML 生成 PDF、導出 PDF、編輯現有 PDF 等,提供了一個完整的工具集,用於在 .NET 環境中處理 PDF 文件。

IronPDF 使 HTML 轉 PDF 變得容易,同時保持布局和樣式不變。 這是從基於 Web 的內容建立 PDF 的絕佳工具,例如報告、發票和文件。 HTML 文件、URL 和 HTML 字串可以無縫轉換為 PDF 文件。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");
        
        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");
        
        // 3. Convert URL to PDF
        var url = "https://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}

將 IronPDF 與 C# Substring 方法結合使用,對於需要在 PDF 轉換前進行文字操作和提取的 PDF 文件生成非常有用。 例如,如果您需要從大型文字塊中提取特定資訊,並以 PDF 格式呈現,可以使用 Substring 方法來隔離所需文字,並使用 IronPDF 將該文字轉換為 PDF 文件。

程式碼範例:從提取的字串生成 PDF

讓我們考慮一種情況,您擁有一個大型文字,其中在指定索引處包含重要資訊,您需要提取此資訊並生成一個包含該資訊的 PDF 文件。 以下是如何使用 IronPDF 和 C# Substring 方法來實現這一目的的逐步範例。

using IronPdf;
using System;

public class PdfGenerator
{
    public static void Main(string[] args)
    {
        // Applying your license for IronPDF
        License.LicenseKey = "License-Key";
        // Original large text from which we need to extract information
        string originalText = "IronPDF helps you generate PDF documents in .NET applications easily. Discover more about IronPDF at the official site.";
        // Using the Substring method to extract the part of the string that talks about IronPDF
        string importantInfo = originalText.Substring(0, 65);  // Extracts the first sentence
        
        // Create a PDF document with IronPDF
        var renderer = new ChromePdfRenderer();
        // Convert the extracted text to PDF
        PdfDocument pdf = renderer.RenderHtmlAsPdf($"<h1>Extracted Information</h1><p>{importantInfo}</p>");
        // Save the PDF to a file
        pdf.SaveAs("ExtractedInfo.pdf");
        // Confirmation output
        Console.WriteLine("PDF generated successfully with extracted information.");
    }
}

C# Substring(它對開發人員的作用):圖 1

此過程顯示了一種整合文字操作和 PDF 建立的簡單方法,這對於需要從較大的文字中提取和呈現特定資訊的報告或文件生成特別有用。

結論

C# Substring(它對開發人員的作用):圖 2

C# 中的 Substring 方法是一個強大的字串操作工具,使開發人員能夠輕鬆根據指定的字元位置提取文字部分。 通過理解和使用這個方法,您可以有效地處理各種文字處理任務。 請記住要考慮邊緣情況並驗證索引,以保持應用程式的穩健性。 IronPDF 提供免費試用讓開發人員探索其功能,並且產品的授權起價為 $999。

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.

...
Read More

Related Articles

Key in blue circle

立即免費取得 30 天試用金鑰

bullet_checked無需信用卡或建立帳號
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費現場演示
Booking Badge related to IronPDF Product Demo

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立