跳至頁尾內容
.NET幫助

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

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

理解 Substring 方法

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

語法和參數

Substring 方法有兩種主要形式:

public string Substring(int startIndex);
public string Substring(int startIndex, int length);
public string Substring(int startIndex);
public string Substring(int startIndex, int length);
public String Substring(Integer startIndex)
public String Substring(Integer startIndex, Integer length)
$vbLabelText   $csharpLabel
  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);
}
// 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);
}
Option Strict On



Public Module Program
    ' Main method demonstrating substring extraction
    Public Sub Main(args As String())
        Dim text As String = "Hello, world!"
        Dim substring As String = text.Substring(7) ' Extract from index 7 to the end
        Console.WriteLine(substring)
    End Sub
End Module
$vbLabelText   $csharpLabel

輸出:

world!

在這個例子中,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);
}
// 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);
}
Option Strict On



Public Module Program
    ' Main method demonstrating substring extraction with specified length
    Public Sub Main(args As String())
        Dim text As String = "Hello, world!"
        Dim substring As String = text.Substring(7, 5) ' Starts at index 7, length of 5
        Console.WriteLine(substring)
    End Sub
End Module
$vbLabelText   $csharpLabel

輸出:

world

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

從字串陣列中檢索子字串

假設您有一個字串陣列,並希望根據指定的字元位置和長度從每個字串中提取子字串。 您可以使用 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);
}
// 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);
}
' Example of extracting substrings from an array of strings
Dim array() As String = { "apple", "banana", "orange" }
For Each str As String In array
	Dim substring As String = str.Substring(1, 3) ' Substring starts from index 1
	Console.WriteLine(substring)
Next str
$vbLabelText   $csharpLabel

這段程式碼將輸出:

ppl
ana
ran

處理邊緣情況

考慮邊緣情況以避免運行時錯誤,如 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.");
    }
}
// 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.");
    }
}
Option Strict On



Public Module Program
    ' Main method with checks to avoid ArgumentOutOfRangeException
    Public Sub Main(args As String())
        Dim text As String = "Hello, world!"
        Dim startIndex As Integer = 7
        Dim length As Integer = 5
        If startIndex >= 0 AndAlso startIndex < text.Length AndAlso startIndex + length <= text.Length Then
            Dim substring As String = text.Substring(startIndex, length)
            Console.WriteLine(substring)
        Else
            Console.WriteLine("Invalid substring parameters.")
        End If
    End Sub
End Module
$vbLabelText   $csharpLabel

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

在 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");
    }
}
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");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "https://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

將 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.");
    }
}
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.");
    }
}
Imports IronPdf
Imports System

Public Class PdfGenerator
	Public Shared Sub Main(ByVal args() As String)
		' Applying your license for IronPDF
		License.LicenseKey = "License-Key"
		' Original large text from which we need to extract information
		Dim originalText As String = "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
		Dim importantInfo As String = originalText.Substring(0, 65) ' Extracts the first sentence

		' Create a PDF document with IronPDF
		Dim renderer = New ChromePdfRenderer()
		' Convert the extracted text to PDF
		Dim pdf As PdfDocument = 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.")
	End Sub
End Class
$vbLabelText   $csharpLabel

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

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

結論

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

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

常見問題

Substring 方法在 C# 中如何運作?

C# 中的 Substring 方法是 String 類的一個函式,使開發者能根據指定的起始索引和選擇性的長度,提取字串的一部分。它有助於將字串分解成更小、更易於管理的部分,以便進一步操作或分析。

Substring 方法的常見用例有哪些?

Substring 方法的常見用例包括從字串中提取特定資料,例如從路徑中獲取檔名或從電子郵件地址中分離域名。它還可以與 IronPDF 程式庫結合使用,將提取的文字轉換為 PDF 文件。

如何將提取的文字轉換為 C# 中的 PDF?

您可以使用 IronPDF 程式庫將提取的文字轉換為 C# 中的 PDF。在使用 Substring 方法提取所需文字後,您可以使用 IronPDF 的方法,如 RenderHtmlAsPdf,建立並保存 PDF 文件。

Substring 方法的兩種主要形式有何不同?

Substring 方法有兩種主要的形式:Substring(int startIndex),將從指定的起始索引處提取文字直到字串結尾;Substring(int startIndex, int length),從起始索引開始提取特定數量的字元。

怎樣才能避免在 C# 中使用 Substring 方法時出錯?

為了防止使用 Substring 方法時出錯,確保起始索引和長度在字串的範圍內。無效的索引會引發 ArgumentOutOfRangeException。在調用此方法前,請始終驗證您的索引。

我可以在陣列元素上使用 Substring 方法嗎?

是的,您可以將 Substring 方法應用於字串陣列中的元素。透過迭代陣列,您可以使用 Substring 方法提取每個字串元素的特定部分。

IronPDF 如何與 Substring 方法整合?

IronPDF 可以與 Substring 方法整合,首先使用 Substring 從字串中提取必要的文字。然後,IronPDF 可以將這些提取的文字轉換為 PDF,這對生成格式化的報告或文件很有用。

using Substring 方法的真實案例是什麼?

using Substring 方法的真實例子是從 URL 或電子郵件中提取使用者 ID。比如,使用 userEmail.Substring(0, userEmail.IndexOf('@')) 提取電子郵件地址的使用者名部分。

using Substring 方法時,您如何驗證索引?

在使用 Substring 方法前,請驗證 startIndex 是否為非負數且小於字串的長度。同時,確保 startIndexlength 的總和不超過字串的總長度,以避免異常。

為什麼理解 Substring 方法對開發人員來說很重要?

理解 Substring 方法對開發人員來說至關重要,因為這是字串操作的基礎,是編程中的常見任務。掌握 Substring 使開發人員能夠有效地處理和操作文字資料,促進資料提取和轉換等任務。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話