.NET 幫助

C# 子字串(開發者如何運作)

發佈 2024年4月29日
分享:

在 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)
VB   C#
  1. public string Substring(起始索引): 這會取得一個子字串,從 startIndex 開始並延續到字串的結尾。

  2. public string Substring(int startIndex, int length):這會從startIndex開始取得指定length的子字串。

涉及的參數有:

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

Substring 方法的工作原理

Substring 方法的過程很簡單。當被調用時,它會從原字符串中提取從給定索引開始的字符。 (startIndex)如果提供 length 參數,該方法將返回指定數目的字符。若沒有 length 參數,則會繼續到字符串結束。使用 C# 的 substring int32 可以確保兩個參數 (起始索引和長度) 被視為整數,強制類型安全並防止潛在的運行時錯誤。

Substring 方法的詳細範例

為了更好地理解 Substring 方法的實現,我們來看一些說明其實際應用的範例。

提取到字符串的末尾

假設你有一個字符串,並且需要從特定索引處提取子字符串到字符串的末尾。以下是如何做到的:

// public static void main
public static void Main(string [] args)
{
    string text = "Hello, world!";
    string substring = text.Substring(7);
    Console.WriteLine(substring);
}
// public static void main
public static void Main(string [] args)
{
    string text = "Hello, world!";
    string substring = text.Substring(7);
    Console.WriteLine(substring);
}
' public static void main
Public Shared Sub Main(ByVal args() As String)
	Dim text As String = "Hello, world!"
	Dim substring As String = text.Substring(7)
	Console.WriteLine(substring)
End Sub
VB   C#

輸出:

world!
world!
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'world!
VB   C#

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

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

現在,讓我們看看一種情況,即同時指定子字符串的起始索引和長度:

public static void Main(string [] args)
{
    string text = "Hello, world!";
    string substring = text.Substring(7, 5);
    Console.WriteLine(substring);
}
public static void Main(string [] args)
{
    string text = "Hello, world!";
    string substring = text.Substring(7, 5);
    Console.WriteLine(substring);
}
Public Shared Sub Main(ByVal args() As String)
	Dim text As String = "Hello, world!"
	Dim substring As String = text.Substring(7, 5)
	Console.WriteLine(substring)
End Sub
VB   C#

輸出:

world
world
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'world
VB   C#

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

從字串陣列獲取子字串

假設你有一個字串陣列,並且你想要從每個字串中根據指定的字符位置和長度提取子字串。你可以使用 foreach 迴圈來遍歷陣列,並對每個字串應用 substring 方法。

string [] array = { "apple", "banana", "orange" };
foreach (string str in array)
{
    string substring = str.Substring(1, 3); // substring starts from index 1
    Console.WriteLine(substring);
}
string [] array = { "apple", "banana", "orange" };
foreach (string str in array)
{
    string substring = str.Substring(1, 3); // substring starts from index 1
    Console.WriteLine(substring);
}
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
VB   C#

此程式碼將輸出:

ppl
ana
ran
ppl
ana
ran
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'ppl ana ran
VB   C#

處理邊界情況

考慮邊界情況對於避免運行時錯誤(如 ArgumentOutOfRangeException)來說非常重要。使用 substring 方法時,必須確保指定的字符位置和長度在原始字符串的範圍內。否則,可能會導致索引超出範圍的異常。您可以檢查原始字符串的長度來避免這樣的異常。以下是一些關鍵點:

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

檢查索引的有效性

為確保您的子字串提取不會造成錯誤,您可以添加檢查:

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.");
    }
}
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.");
    }
}
Public Shared Sub Main(ByVal 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
VB   C#

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

將 IronPDF 與 C# 中的 Substring 整合以動態生成 PDF

IronPDF 是一個強大的 PDF 庫,允許開發人員直接在他們的 .NET 應用程式中創建、操作和渲染 PDF 文件。它允許 HTML 轉換為 PDF 幫助建立自定義和美觀的 PDF 文件。IronPDF 支援一系列 PDF 操作,包括從 HTML 生成 PDF、導出 PDF、編輯現有 PDF 等,提供了在 .NET 環境中處理 PDF 文件的全面工具包。

IronPDF 使轉換 HTML轉PDF 容易,同時保持佈局和樣式不變。這是一個從基於網頁的內容(如報告、發票和文檔)生成PDF的絕佳工具。HTML文件、網址和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 = "http://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 = "http://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 = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

將 IronPDF 與 C# Substring 方法結合使用,在生成需要文本操作和提取的 PDF 文檔之前,可以非常有用。例如,如果您需要從一大段文本中提取特定信息並將其以 PDF 格式呈現,可以使用 Substring 方法來隔離所需的文本,並使用 IronPDF 將此文本轉換為 PDF 文檔。

代码示例:从提取的字符串生成 PDF

讓我們考慮一個場景,你擁有一個包含重要資訊的大文本,其中在指定索引處有重要資訊,你需要提取這些資訊並生成一個 PDF 文件。以下是一個逐步示例,展示如何使用 IronPDF 和 C# 的 Substring 方法達成此目標。

using IronPdf;
using System;
public class PdfGenerator
{
    public static void Main(string [] args)
    {
        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)
    {
        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)
		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
VB   C#

C# 子字串(對開發者的運作方式):圖 1

此過程展示了一種簡單直接的文本操作和 PDF 創建方法,這對於生成報告或文件特別有用,因為這些報告或文件需要從較大文本中提取並呈現特定信息。

結論

C# 子字串(開發者如何使用):圖 2

C# 中的 Substring 方法是進行字符串操作的強大工具,讓開發人員可以根據指定的字符位置輕鬆地提取文本的一部分部分。通過理解和利用此方法,你可以有效地處理各種文本處理任務。記得考慮邊緣情況並驗證索引,以保持應用程序的健壯性。IronPDF 提供了 免費試用 供開發人員探索其功能,產品授權費用起價為 $749。

< 上一頁
C# 四捨五入到小數點後第 2 位(開發人員如何操作)
下一個 >
C#選用參數(對開發人員的運作方式)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >