跳過到頁腳內容
.NET HELP

IndexOf C# (How It Works For Developers)

IndexOf 簡介

C# 中的 IndexOf 方法是用於字串操作和搜尋作業的基本工具。 它有助於定位特定字元或子串在另一個字串中的字元位置。 IndexOf 的有效性體現在它能夠提供指定 Unicode 字元或字串首次出現時的基於零的索引,增強了它在文字資料處理上的實用性。

此方法可搜尋單個字元,包括 Unicode 字元或字串,為各種程式設計需求提供彈性。 在本文中,我們將學習 IndexOf 方法的基礎知識以及 IronPDF 函式庫的功能

基本語法和用法

IndexOf 的語法

C# 中 IndexOf 的基本語法相當直接。 該方法有多種重載,允許彈性的搜尋參數,包括指定搜尋的起點和檢視的字元數。

最簡單的形式是 public int IndexOf(char value) 會搜尋單一字元。 還有一個 public int IndexOf(string value) 用來搜尋子串。 進階版本允許指定起始索引或同時指定起始索引和計數,增強了該方法在搜尋作業中的通用性。

使用 IndexOf

為了說明 IndexOf 的用法,請考慮您需要在較大的字串中找出一個字元或子字串的位置的情況。 下面是一個簡單的例子:

public static void Main(string[] args)
{
    string str = "Hello, world!";
    int index = str.IndexOf('o');
    Console.WriteLine("The index of 'o' is: " + index);
}
public static void Main(string[] args)
{
    string str = "Hello, world!";
    int index = str.IndexOf('o');
    Console.WriteLine("The index of 'o' is: " + index);
}
$vbLabelText   $csharpLabel

依照此範例,該片段會找出第一次出現的字元 'o',並顯示以下指出其位置的輸出。 輸出內容將包括

o' 的索引為4

請注意,索引是以 0 為基礎,也就是第一個字串字元從索引 0 開始。

進階搜尋

指定開始索引

C# 中的 String IndexOf 方法是字串操作的核心工具,擅長於在另一個字串中找出指定的字元或子字串。 當您有興趣尋找某個字元或子字串的後續出現記錄時,此功能尤其有用。 舉例來說

string value = "Brown fox jumps over";
int startIndex = value.IndexOf('o') + 1;
int index = value.IndexOf('o', startIndex);
Console.WriteLine("The index of the second 'o' is: " + index);
string value = "Brown fox jumps over";
int startIndex = value.IndexOf('o') + 1;
int index = value.IndexOf('o', startIndex);
Console.WriteLine("The index of the second 'o' is: " + index);
$vbLabelText   $csharpLabel

首先,程式碼會找出第一次出現的 'o",然後從第一次找到的索引後開始搜尋下一個 "o'。

當執行程式碼時,控制台輸出為:

第二個 'o' 的索引為 7

使用開始索引和計數進行搜尋

如以下範例所示,更詳細的查詢涉及同時指定開始索引和計數,以簡化搜尋。 這將搜尋範圍限制在字串內的特定範圍,以最佳化效能與精確度。 以下是執行方式:

string sample = "Sample text for testing";
int startindex = 7;
int count = 10;
int result = sample.IndexOf("text", startindex, count);
Console.WriteLine("Index of 'text': " + result);
string sample = "Sample text for testing";
int startindex = 7;
int count = 10;
int result = sample.IndexOf("text", startindex, count);
Console.WriteLine("Index of 'text': " + result);
$vbLabelText   $csharpLabel

此片段在指定範圍內搜尋"text"一詞,展示此方法在縮小大字串搜尋範圍的彈性。

執行此程式碼時,控制台會輸出:

文字"索引: 7

性能考慮因素索引

IndexOf 作為字串查詢的有力工具,掌握它對資料結構效能的影響是非常重要的。 在引擎蓋下,IndexOf 執行的是線性搜尋,這表示它會檢查從起點開始的每個字元,直到找到符合的字元或到達搜尋範圍的終點為止。

對於大型字串或複雜的搜尋,尤其是涉及 Unicode 字元的搜尋,可能會影響效能。 因此,優化開始索引和計數參數可以大幅提升 IndexOf 作業的效率。

使用 IndexOf 處理特殊情況

在使用 IndexOf 時,必須處理字串搜尋作業中可能出現的特殊情況。 這包括搜尋目標字串中不存在的字元或子串、瞭解 IndexOf 對空字串的行為,以及處理大小寫敏感性。

搜尋不存在的元素

一種常見的情況是嘗試尋找字串中不存在的字元或子字串。 在這些情況下,該方法會返回結果值 -1 表示搜尋結果。 這是需要檢查的重要條件,以避免程式碼出錯。 以下是處理方法:

string phrase = "Searching for a missing character";
int index = phrase.IndexOf('x'); // 'x' does not exist in the string
if (index == -1)
{
    Console.WriteLine("未找到字元。");
}
else
{
    Console.WriteLine("Character found at index: " + index);
}
string phrase = "Searching for a missing character";
int index = phrase.IndexOf('x'); // 'x' does not exist in the string
if (index == -1)
{
    Console.WriteLine("未找到字元。");
}
else
{
    Console.WriteLine("Character found at index: " + index);
}
$vbLabelText   $csharpLabel

執行此程式碼時,控制台會輸出:

未找到字元。

處理空字串

另一種特殊情況是搜尋字串或目標字串為空時。 IndexOf 將任何字串(即使是空字串)的開頭視為空子串的有效位置。 因此,在任何字串中搜尋空字串都會回傳 0,表示該字串的起始位置。 反之,在空字串內搜尋任何非空的子字串,都會回傳 -1,因為沒有可能匹配。 了解這種行為對於準確的搜尋結果至關重要。

大小寫敏感度與文化考量

預設情況下,IndexOf 方法是區分大小寫的。這表示搜尋 'a" 與搜尋 "A' 是不同的。 根據應用程式的需求,您可能需要執行不區分大小寫的搜尋。 這可以透過使用 IndexOf 方法來實現,該方法接受 StringComparison 枚舉作為參數。 此外,IndexOf 尊重字串比較的文化規則,這會影響 Unicode 字元的搜尋結果。 對於有特定文化或語言需求的應用程式,可以使用接受 CultureInfo 物件的重載來調整此行為。

範例:區分大小寫搜尋

string data = "Case-Insensitive Search Example";
int indexInsensitive = data.IndexOf("search", StringComparison.OrdinalIgnoreCase);
if (indexInsensitive >= 0)
{
    Console.WriteLine("Substring found at index: " + indexInsensitive);
}
else
{
    Console.WriteLine("Substring not found.");
}
string data = "Case-Insensitive Search Example";
int indexInsensitive = data.IndexOf("search", StringComparison.OrdinalIgnoreCase);
if (indexInsensitive >= 0)
{
    Console.WriteLine("Substring found at index: " + indexInsensitive);
}
else
{
    Console.WriteLine("Substring not found.");
}
$vbLabelText   $csharpLabel

此程式碼片段示範如何執行大小寫不敏感的搜尋,以確保大小寫的變化不會影響在字串中找出子串的能力。

IronPDF:C# PDF 函式庫

IndexOf C# (How It Works For Developers):圖 1 - IronPdf 網頁

IronPDF是專為 .NET Framework 設計的綜合函式庫,旨在方便使用 C# 創建、編輯和處理 PDF 文件。 它的突出之處在於 使用 IronPDF、CSS、JavaScript 和圖像直接從 HTML 生成 PDF 的方法,簡化了轉換過程,確保開發人員能快速高效地製作文件。 本程式庫與各種 .NET 專案類型相容,包括 Blazor 和 WebForms 等網頁應用程式、使用 WPF 和 MAUI 的桌面應用程式等。 它支援各種環境和平台,例如 Windows、Linux、Mac 和 Docker,使其能滿足不同的開發需求。

IronPDF 擅長於 HTML 至 PDF 的轉換,可確保精確保留原始版面與樣式。 它非常適合從網頁內容(如報告、發票和文件)建立 PDF。 IronPDF 支援 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");
    }
}
$vbLabelText   $csharpLabel

程式碼範例

請確保您的專案已安裝 IronPdf,才能使用本範例。 如果沒有,您可以使用命令透過 NuGet Package Manager 輕鬆新增:

Install-Package IronPdf

要將 IronPDF 的功能與 C# 中的 IndexOf 操作相整合,您通常會考慮以下情況:您有興趣在 PDF 文件中找到特定的文字,也許會以某種方式操作或與該文字互動。

下面的範例是概念性的,重點在於從 PDF 擷取文字,然後使用 IndexOf 方法找出特定子串在該文字中的位置。 請記住,IronPDF 的 API 可能無法直接揭露名為 IndexOf 的方法,因為這是 C# 中 string 類的方法。

using IronPdf;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Create an instance of the IronPDF PDF document reader
        var pdfDocument = PdfDocument.FromFile("path/to/your/document.pdf");
        // Extract all text from the PDF document
        var allText = pdfDocument.ExtractAllText();
        // The text you want to search for in the PDF document
        string searchText = "specific text";
        // Use IndexOf to find the position of searchText in the extracted text
        int position = allText.IndexOf(searchText);
        if (position != -1)
        {
            Console.WriteLine($"Text found at position: {position}");
            // You can perform further operations here, such as highlighting the text in the PDF if supported by IronPDF
        }
        else
        {
            Console.WriteLine("Text not found in the PDF document.");
        }
    }
}
using IronPdf;
using System;

class Program
{
    static void Main(string[] args)
    {
        // Create an instance of the IronPDF PDF document reader
        var pdfDocument = PdfDocument.FromFile("path/to/your/document.pdf");
        // Extract all text from the PDF document
        var allText = pdfDocument.ExtractAllText();
        // The text you want to search for in the PDF document
        string searchText = "specific text";
        // Use IndexOf to find the position of searchText in the extracted text
        int position = allText.IndexOf(searchText);
        if (position != -1)
        {
            Console.WriteLine($"Text found at position: {position}");
            // You can perform further operations here, such as highlighting the text in the PDF if supported by IronPDF
        }
        else
        {
            Console.WriteLine("Text not found in the PDF document.");
        }
    }
}
$vbLabelText   $csharpLabel

此程式碼片段提供開啟 PDF、擷取其文字內容,以及在該內容中搜尋特定字串的基本架構。

當執行此程式碼時,控制台會輸出:Text found at position:1046

結論

IndexOf C# (How It Works For Developers):圖 2 - IronPdf 授權頁面

總而言之,C# 中的 IndexOf 方法是程式設計師工具包中不可或缺的一部分,它提供了在字串中有效搜尋字元或子字串的能力。 透過各種重載,它提供了處理各種文字處理工作所需的靈活性,使其成為處理字串資料的開發人員不可或缺的方法。 從 免費試用 IronPDF 開始,然後探討 IronPDF 授權選項,從 $799 開始。

常見問題解答

如何使用 C# 中的 IndexOf 方法進行字串操作?

C# 中的 IndexOf 方法用於定位特定字元或子串在另一個字串中的位置。它會返回指定值首次出現時的基於零的索引,因此對於字串操作任務來說非常重要。

C# 中 IndexOf 方法有哪些不同的重載?

C# 中的 IndexOf 方法有幾個重載,例如:IndexOf(char value) 用於搜尋單一字元,IndexOf(string value) 用於子串,以及額外的重載來指定起始索引和計數,以滿足進階的搜尋需求。

我可以使用 C# 中的 IndexOf 方法執行不區分大小寫的搜尋嗎?

是的,您可以透過使用 StringComparison.OrdinalIgnoreCase 參數,使用 IndexOf 方法執行大小寫不敏感的搜尋,確保大小寫的變化不會影響結果。

C# 中 IndexOf 方法如何處理不存在的元素?

如果未找到字元或子字串,IndexOf 方法會返回 -1。必須檢查此結果,以處理搜尋值在字串中不存在的情況。

IronPDF 如何與 C# IndexOf 方法整合以提取 PDF 文字?

IronPDF 可讓您從 PDF 文件中抽取文字。擷取完成後,您可以使用 IndexOf 方法搜尋文字中的特定子串,方便進一步的操作或分析。

在 C# 中使用 IndexOf 時有哪些效能考量?

IndexOf 執行的是線性搜尋,會檢查每個字元,直到找到符合的字元或搜尋範圍的結束為止。優化開始索引和計數參數可以提升效能,尤其是對於大型字串。

C# 中 IndexOf 方法如何處理空字串?

在任何字串中搜尋空字串時,IndexOf 會返回 0,表示字串的起點。反之,在空字串中搜尋任何非空的子字串,則會返回 -1。

在 C# 中使用 IndexOf 時,如何考慮文化或語言需求?

IndexOf 尊重字串比較的文化規則,會影響 Unicode 字元的結果。對於特定的文化需求,請使用接受 CultureInfo 物件的重載來調整方法的行為。

在 IndexOf 方法中指定開始索引和計數有什麼意義?

在 IndexOf 方法中指定起始索引和次數,可以將搜尋範圍限制在字串的特定區段,提高搜尋效率,並實現更有針對性的子串搜尋。

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

Jacob Mellor 是 Iron Software 的首席技術長,也是開創 C# PDF 技術的有遠見的工程師。作為 Iron Software 核心程式碼庫背後的原始開發人員,他從公司成立之初就塑造了公司的產品架構,與首席執行官 Cameron Rimington 一起將公司轉型為一家 50 多人的公司,為 NASA、Tesla 和全球政府機構提供服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽工程學士學位 (BEng)(1998-2001 年)。

Jacob 於 1999 年在倫敦開設了他的第一家軟體公司,並於 2005 年創建了他的第一個 .NET 元件,之後,他專門解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF & Iron Suite for .NET 函式庫在全球的 NuGet 安裝量已超過 3000 萬次,他的基礎程式碼持續為全球使用的開發人員工具提供動力。Jacob 擁有 25 年的商業經驗和 41 年的編碼專業知識,他一直專注於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代的技術領導者。