.NET 帮助

C# 子字符串(开发人员如何使用)

发布 2024年四月29日
分享:

在 C# 中 Substring 方法 是操作字符串的重要工具。该函数允许开发人员根据指定的字符位置提取字符串的一部分。本指南旨在详细解释公共字符串 Substring 方法和 IronPDF 库提供详细的示例和解释,帮助初学者充分了解其用法和功能。

了解子串方法

C# 中的 Substring 方法是字符串类的一个成员,允许根据指定参数从第一个字符开始进行操作。它用于检索字符串的一部分,从指定的索引开始,也可选择指定的位置。该方法的语法简单明了,因此可以在任何需要操作字符串的编码场景中轻松实现。

语法和参数

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. 公共字符串 Substring(int startIndex):这将检索一个从startIndex开始一直到字符串末尾的子串。

  2. 公共字符串 Substring(int startIndex, int length):这将检索从startIndex开始并具有指定长度的子串。

涉及的参数有

  • int startIndex:这是子串开始的零基索引。
  • int length: (可选的) 是第二个参数。这是要包含在返回子串中的字符数。

子串方法的工作原理

子串方法的过程非常简单。调用时,它会从原始字符串中提取从给定索引开始的字符 (startIndex).如果提供 length 参数,该方法将返回指定的字符数。如果不提供length参数,该方法将持续到字符串的末尾。在 C# 中使用 substring int32** 可确保两个参数 (startIndex 和长度) 被视为整数,从而确保了类型安全,避免了潜在的运行时错误。

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#

在本例中,子串方法从索引 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&num 中的 Substring 集成,实现动态 PDF 创建

IronPDF 是一个功能强大的 PDF 库,允许开发人员直接在其 .NET 应用程序中创建、处理和渲染 PDF 文档。它允许 HTML 转换为 PDF 帮助创建定制和美观的PDF文档。IronPDF支持一系列PDF操作,包括从HTML生成PDF、导出PDF、编辑现有PDF等,提供了一个全面的工具包,用于在.NET环境中处理PDF文件。

IronPDF使转换 HTML 转 PDF 轻松,同时保持布局和样式完整。这是一个从网络内容生成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 = "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文档非常有用。例如,如果您需要从一大段文本中提取特定信息并将其呈现为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# 四舍五入到小数点后两位(开发人员指南)
下一步 >
C# 可选参数 (开发人员如何使用)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >