跳至页脚内容
.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);
}
' Main method demonstrating substring extraction
Public Shared Sub Main(ByVal 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
$vbLabelText   $csharpLabel

输出:

world!

在此示例中,Substring 方法从索引 7 开始,这对应于 "world!" 中的 '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);
}
' Main method demonstrating substring extraction with specified length
Public Shared Sub Main(ByVal 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
$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.");
    }
}
' Main method with checks to avoid ArgumentOutOfRangeException
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
$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 为开发者提供免费试用以探索其功能,产品的授权从 $799起。

常见问题解答

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 从字符串中提取必要的文本,然后将此提取文本转换为 PDF,这对于生成格式化的报告或文档很有用。

在现实场景中使用 Substring 方法的例子是什么?

使用 Substring 方法的一个现实例子是从 URL 或电子邮件中提取用户 ID。例如,使用 userEmail.Substring(0, userEmail.IndexOf('@')) 提取电子邮件地址的用户名部分。

使用 Substring 方法时如何验证索引?

使用 Substring 方法前,验证 startIndex 非负数且小于字符串长度。同时,确保 startIndexlength 的总和不超过字符串总长度,以避免异常。

为什么理解 Substring 方法对开发人员很重要?

理解 Substring 方法对开发人员至关重要,因为它是字符串操作的重要组成部分,这是编程中的常见任务。掌握 Substring 可以让开发人员高效地处理和操作文本数据,便于执行数据提取和转换等任务。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。