跳至頁尾內容
開發者更新

C# string.Co/ntains 用法(開發者完整指南)

在今天的開發世界中,對於需要處理文件、表單或報告的應用程式來說,處理PDF是一個常見的需求。 無論您是在構建電子商務平台、文件管理系統,還是僅僅需要處理發票,從PDF中提取和搜尋文字都是至關重要的。 本文將指導您如何在.NET專案中使用C# string.Contains()IronPDF搜尋和提取PDF文件中的文字。

字串比較與指定子串

在執行搜尋時,您可能需要根據特定的字串子串要求來執行字串比較。 在這種情況下,C#提供了像是string.Contains()這樣的選項,這是最簡單的比較形式之一。

如果您需要指定是否忽略大小寫,您可以使用StringComparison列舉。 這讓您可以選擇您想要的字串比較型別,例如序數比較或不區分大小寫的比較。

如果您想要處理字串中的特定位置,例如第一個字元位置或最後一個字元位置,您可以使用Substring來隔離字串的某些部分以進行進一步處理。

如果您正在尋找空字串檢查或其他邊緣情況,請確保在您的邏輯中處理這些場景。

如果您正在處理大型文件,優化文字提取的起始位置非常有用,僅提取相關部分而不是整個文件。 這尤其有用,如果您希望避免記憶體過載和處理時間過長。

如果您不確定比較規則的最佳方法,請考慮特定方法的性能以及您希望搜尋在不同場景中的行為(例如,匹配多個術語,處理空格等)。

如果您的需求超出簡單的子串檢查,需要更高級的模式匹配,請考慮使用正規表達式,這在處理PDF時提供了顯著的靈活性。

如果您還沒試過,今天就試試IronPDF的免費試用,探索它的功能,了解它如何簡化您的PDF處理任務。 無論您是在構建文件管理系統、處理發票,還是僅需從PDF中提取資料,IronPDF都是完成這項工作的理想工具。

什麼是IronPDF以及為什麼您應該使用它?

IronPDF是一個強大的程式庫,旨在幫助在.NET生態系統中處理PDF的開發人員。 它使您能夠輕鬆建立、讀取、編輯和操作PDF文件,而無需依賴外部工具或複雜配置。

IronPDF概述

IronPDF為在C#應用程式中處理PDF提供了廣泛的功能。 一些主要功能包括:

  • 文字提取:從PDF中提取純文字或結構化資料。
  • PDF編輯:通過新增、刪除或編輯文字、圖片和頁面來修改現有PDF。
  • PDF轉換:將HTML或ASPX頁面轉換為PDF或反之亦然。
  • 表單處理:提取或填充互動式PDF表單中的表單欄位。

IronPDF設計簡單易用,但靈活到足以處理涉及PDF的複雜場景。 它與.NET Core和.NET Framework無縫配合,是任何基於.NET項目的完美選擇。

安裝 IronPDF

要使用 IronPDF,請通過 Visual Studio 的 NuGet 包管理器進行安裝:

Install-Package IronPdf

How to Search Text in PDF Files Using C

在深入搜尋PDF之前,讓我們先了解如何使用IronPDF從PDF中提取文字。

使用IronPDF基本的PDF文字提取

IronPDF提供了一個簡單的API來從PDF文件中提取文字。 這讓您可以輕鬆在PDF中搜尋特定內容。

以下範例演示瞭如何使用IronPDF從PDF中提取文字:

using IronPdf;
using System;

public class Program
{
    public static void Main(string[] args)
    {
        // Load the PDF from a file
        PdfDocument pdf = PdfDocument.FromFile("invoice.pdf");
        // Extract all text from the PDF
        string text = pdf.ExtractAllText();
        // Optionally, print the extracted text to the console
        Console.WriteLine(text);
    }  
}
using IronPdf;
using System;

public class Program
{
    public static void Main(string[] args)
    {
        // Load the PDF from a file
        PdfDocument pdf = PdfDocument.FromFile("invoice.pdf");
        // Extract all text from the PDF
        string text = pdf.ExtractAllText();
        // Optionally, print the extracted text to the console
        Console.WriteLine(text);
    }  
}
Imports IronPdf
Imports System

Public Class Program
	Public Shared Sub Main(ByVal args() As String)
		' Load the PDF from a file
		Dim pdf As PdfDocument = PdfDocument.FromFile("invoice.pdf")
		' Extract all text from the PDF
		Dim text As String = pdf.ExtractAllText()
		' Optionally, print the extracted text to the console
		Console.WriteLine(text)
	End Sub
End Class
$vbLabelText   $csharpLabel

在此範例中,ExtractAllText()方法提取了PDF文件中的所有文字。 然後,這些文字可以被處理用來搜尋特定關鍵字或短語。

使用string.Contains()進行文字搜尋

一旦您從PDF中提取了文字,您可以使用C#內建的string.Contains()方法來搜尋特定的詞或短語。

string.Contains()方法返回一個布林值,指示一個指定的字串是否存在於一個字串中。 這對基本文字搜尋特別有用。

以下是如何使用string.Contains()在提取的文字中搜尋一個關鍵字:

bool isFound = text.Contains("search term", StringComparison.OrdinalIgnoreCase);
bool isFound = text.Contains("search term", StringComparison.OrdinalIgnoreCase);
Dim isFound As Boolean = text.Contains("search term", StringComparison.OrdinalIgnoreCase)
$vbLabelText   $csharpLabel

實用範例:如何檢查C#字串是否在PDF文件中包含關鍵詞

讓我們進一步分解這個實用範例。 假設您想找出特定的發票號碼是否存在於PDF發票文件中。

這是您如何實現這一點的完整範例:

using IronPdf;
using System;

public class Program
{
    public static void Main(string[] args)
    {
        string searchTerm = "INV-12345";
        // Load the PDF from a file
        PdfDocument pdf = PdfDocument.FromFile("exampleInvoice.pdf");
        // Extract all text from the PDF
        string text = pdf.ExtractAllText();
        // Search for the specific invoice number
        bool isFound = text.Contains(searchTerm, StringComparison.OrdinalIgnoreCase);
        // Provide output based on whether the search term was found
        if (isFound)
        {
            Console.WriteLine($"Invoice number: {searchTerm} found in the document");
        }
        else
        {
            Console.WriteLine($"Invoice number {searchTerm} not found in the document");
        }
    }  
}
using IronPdf;
using System;

public class Program
{
    public static void Main(string[] args)
    {
        string searchTerm = "INV-12345";
        // Load the PDF from a file
        PdfDocument pdf = PdfDocument.FromFile("exampleInvoice.pdf");
        // Extract all text from the PDF
        string text = pdf.ExtractAllText();
        // Search for the specific invoice number
        bool isFound = text.Contains(searchTerm, StringComparison.OrdinalIgnoreCase);
        // Provide output based on whether the search term was found
        if (isFound)
        {
            Console.WriteLine($"Invoice number: {searchTerm} found in the document");
        }
        else
        {
            Console.WriteLine($"Invoice number {searchTerm} not found in the document");
        }
    }  
}
Imports IronPdf
Imports System

Public Class Program
	Public Shared Sub Main(ByVal args() As String)
		Dim searchTerm As String = "INV-12345"
		' Load the PDF from a file
		Dim pdf As PdfDocument = PdfDocument.FromFile("exampleInvoice.pdf")
		' Extract all text from the PDF
		Dim text As String = pdf.ExtractAllText()
		' Search for the specific invoice number
		Dim isFound As Boolean = text.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)
		' Provide output based on whether the search term was found
		If isFound Then
			Console.WriteLine($"Invoice number: {searchTerm} found in the document")
		Else
			Console.WriteLine($"Invoice number {searchTerm} not found in the document")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

輸入PDF

C#字串包含(它如何為開發人員工作):圖1

控制台輸出

C#字串包含(它如何為開發人員工作):圖2

在這個範例中:

  • 我們載入PDF文件並提取其文字。
  • 然後,我們使用INV-12345
  • 由於StringComparison.OrdinalIgnoreCase,搜尋不區分大小寫。

使用正規表達式增強搜尋

雖然string.Contains()適用於簡單的子串搜尋,但您可能想執行更複雜的搜尋,例如找到模式或一系列關鍵字。 為此,您可以使用正規表達式。

以下是使用正規表達式搜尋PDF文字中的任何有效發票號碼格式的範例:

using IronPdf;
using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main(string[] args)
    {
        // Define a regex pattern for a typical invoice number format (e.g., INV-12345)
        string pattern = @"INV-\d{5}";
        // Load the PDF from a file
        PdfDocument pdf = PdfDocument.FromFile("exampleInvoice.pdf");
        // Extract all text from the PDF
        string text = pdf.ExtractAllText();
        // Perform the regex search
        Match match = Regex.Match(text, pattern);
        // Check if a match was found
        if (match.Success)
        {
            Console.WriteLine($"Invoice number found: {match.Value}");
        }
        else
        {
            Console.WriteLine("No matching invoice number found.");
        }
    }  
}
using IronPdf;
using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main(string[] args)
    {
        // Define a regex pattern for a typical invoice number format (e.g., INV-12345)
        string pattern = @"INV-\d{5}";
        // Load the PDF from a file
        PdfDocument pdf = PdfDocument.FromFile("exampleInvoice.pdf");
        // Extract all text from the PDF
        string text = pdf.ExtractAllText();
        // Perform the regex search
        Match match = Regex.Match(text, pattern);
        // Check if a match was found
        if (match.Success)
        {
            Console.WriteLine($"Invoice number found: {match.Value}");
        }
        else
        {
            Console.WriteLine("No matching invoice number found.");
        }
    }  
}
Imports IronPdf
Imports System
Imports System.Text.RegularExpressions

Public Class Program
	Public Shared Sub Main(ByVal args() As String)
		' Define a regex pattern for a typical invoice number format (e.g., INV-12345)
		Dim pattern As String = "INV-\d{5}"
		' Load the PDF from a file
		Dim pdf As PdfDocument = PdfDocument.FromFile("exampleInvoice.pdf")
		' Extract all text from the PDF
		Dim text As String = pdf.ExtractAllText()
		' Perform the regex search
		Dim match As Match = Regex.Match(text, pattern)
		' Check if a match was found
		If match.Success Then
			Console.WriteLine($"Invoice number found: {match.Value}")
		Else
			Console.WriteLine("No matching invoice number found.")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

此程式碼將搜尋符合模式INV-XXXXX的任何發票號碼,其中XXXXX是一系列數字。

在.NET中處理PDF的最佳實踐

在處理PDF文件時,特別是大型或複雜文件,有一些最佳實踐需要注意:

優化文字提取

  • 處理大型PDF:如果您正在處理大型PDF,提取小段文字(按頁)是一個好主意,以減少記憶體使用,並提高性能。
  • 處理特殊編碼:注意PDF中的編碼和特殊字元。 IronPDF通常能夠很好地處理這個問題,但複雜的佈局或字型可能需要額外處理。

將IronPDF整合到.NET項目中

IronPDF可以輕鬆整合到.NET項目中。 通過NuGet下載和安裝IronPDF程式庫後,只需將其導入到您的C#程式碼中,如上例所示。

IronPDF的靈活性使您可以構建複雜的文件處理工作流程,例如:

  • 搜尋和提取表單中的資料。
  • 將HTML轉換為PDF並提取內容。
  • 根據使用者輸入或資料庫資料建立報告。

結論

IronPDF使處理PDF變得簡單且高效,特別是當您需要在PDF中提取和搜尋文字時。 通過結合C#的string.Contains()方法與IronPDF的文字提取功能,您可以迅速在您的.NET應用程式中搜尋和處理PDF。

如果您還沒試過,今天就試試IronPDF的免費試用,探索它的功能,了解它如何簡化您的PDF處理任務。 無論您是在構建文件管理系統、處理發票,還是僅需從PDF中提取資料,IronPDF都是完成這項工作的理想工具。

要開始使用IronPDF,下載免費試用並親身體驗其強大的PDF操作功能。 存取IronPDF的網站,今天就開始。

常見問題

如何使用 C# 的 string.Contains() 在 PDF 文件中搜尋文字?

您可以使用 C# 的 string.Contains() 結合 IronPDF 在 PDF 文件中搜尋特定文字。首先,使用 IronPDF 的文字提取功能從 PDF 中提取文字,然後應用 string.Contains() 找到所需的文字。

using IronPDF 於 .NET 中進行 PDF 文字提取的好處是什麼?

IronPDF 提供了一個易於使用的 API 來從 PDF 中提取文字,這對於需要高效處理文件的應用程式至關重要。它簡化了流程,使開發人員能夠專注於實現業務邏輯,而不是處理複雜的 PDF 操作。

如何使用 C# 確保在 PDF 中進行不區分大小寫的文字搜尋?

要在 PDF 文件中進行不區分大小寫的文字搜尋,使用 IronPDF 提取文字,然後使用 C# 的 string.Contains() 方法結合 StringComparison.OrdinalIgnoreCase 忽略搜尋過程中的大小寫區別。

哪些情況需要使用正則表達式而不是 string.Contains()?

當您需要在從 PDF 提取出的文字中搜尋複雜模式或多個關鍵字時,正則表達式比 string.Contains() 更適合。正則表達式提供的高級模式匹配功能是簡單字串搜尋無法實現的。

如何在從大型 PDF 文件中提取文字時優化性能?

為了在從大型 PDF 文件中提取文字時優化性能,考慮將文件分成較小的部分進行處理,例如逐頁進行。此方法可以降低記憶體使用,並透過防止資源過載來提升系統性能。

IronPDF 是否與 .NET Core 和 .NET Framework 相容?

是的,IronPDF 與 .NET Core 和 .NET Framework 皆相容,使其能應用於各種 .NET 應用程式中。此相容性確保它能整合至不同的專案型別中而不會有相容性問題。

如何開始在 .NET 專案中使用 PDF 程式庫?

要在 .NET 專案中開始使用 IronPDF,可以在 Visual Studio 的 NuGet 套件管理器中安裝它。安裝後,您可以將它匯入 C# 程式碼庫中,並利用其功能,如文字提取和 PDF 操作,以滿足您的文件處理需求。

IronPDF 的 PDF 操作主要功能有哪些?

IronPDF 提供一系列 PDF 操作功能,包括文字提取、PDF 編輯和轉換。這些功能可以幫助開發人員有效地處理 PDF,簡化表單處理和文件生產等流程於 .NET 應用程式中。

IronPDF 如何簡化 .NET 應用程式中的 PDF 處理?

IronPDF 提供了一個完整的 API 開發介面,讓開發人員能輕鬆地建立、編輯和從 PDF 文件中提取資料。這消除了複雜配置的需用,並使 .NET 應用程式內有高效率的文件處理工作流程。

如何在 .NET 專案中安裝 IronPDF?

可使用 Visual Studio 的 NuGet 套件管理器在 .NET 專案中安裝 IronPDF。使用命令:Install-Package IronPdf 將 IronPDF 新增到您的專案中,開始運用其 PDF 操作功能。

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天。
聊天
電子郵件
給我打電話