跳過到頁腳內容
.NET幫助

IndexOf C#(對於開發者的運行原理)

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);
}
Public Shared Sub Main(ByVal args() As String)
	Dim str As String = "Hello, world!"
	Dim index As Integer = str.IndexOf("o"c)
	Console.WriteLine("The index of 'o' is: " & index)
End Sub
$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);
Dim value As String = "Brown fox jumps over"
Dim startIndex As Integer = value.IndexOf("o"c) + 1
Dim index As Integer = value.IndexOf("o"c, 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);
Dim sample As String = "Sample text for testing"
Dim startindex As Integer = 7
Dim count As Integer = 10
Dim result As Integer = 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);
}
Imports System

Dim phrase As String = "Searching for a missing character"
Dim index As Integer = phrase.IndexOf("x"c) ' 'x' does not exist in the string
If index = -1 Then
    Console.WriteLine("未找到字元。")
Else
    Console.WriteLine("Character found at index: " & index)
End If
$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.");
}
Dim data As String = "Case-Insensitive Search Example"
Dim indexInsensitive As Integer = data.IndexOf("search", StringComparison.OrdinalIgnoreCase)
If indexInsensitive >= 0 Then
	Console.WriteLine("Substring found at index: " & indexInsensitive)
Else
	Console.WriteLine("Substring not found.")
End If
$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");
    }
}
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
$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.");
        }
    }
}
Imports IronPdf
Imports System

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create an instance of the IronPDF PDF document reader
		Dim pdfDocument = PdfDocument.FromFile("path/to/your/document.pdf")
		' Extract all text from the PDF document
		Dim allText = pdfDocument.ExtractAllText()
		' The text you want to search for in the PDF document
		Dim searchText As String = "specific text"
		' Use IndexOf to find the position of searchText in the extracted text
		Dim position As Integer = allText.IndexOf(searchText)
		If position <> -1 Then
			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.")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

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

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

結論

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

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

常見問題解答

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

C# 中的 IndexOf 方法用於找到特定字符或子串在另一個字串中的位置。它返回指定值首次出現的零基索引,這對於字串操作任務至關重要。

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

C# 中的 IndexOf 方法有多種重載,例如用於單個字符的IndexOf(char value),用於子串的IndexOf(string value),以及用於指定起始索引和計數的其他重載,以滿足更高級的搜索需求。

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

是的,您可以通過使用StringComparison.OrdinalIgnoreCase參數進行不區分大小寫的搜索,以確保大寫變化不影響結果。

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核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我