.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' 的首次出現,顯示出以下輸出以指示其位置。 輸出結果將是:

The index of 'o' is: 4
The index of 'o' is: 4
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'The index @of "o"c is: 4
$vbLabelText   $csharpLabel

請注意,索引是從零開始的,這意味著第一個字符串字符從索引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'。

當程式碼運行時,控制台輸出的內容是:

The index of the second 'o' is 7
The index of the second 'o' is 7
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'The index @of the second "o"c is 7
$vbLabelText   $csharpLabel

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

更詳細的查詢可以透過指定起始索引和計數來進行,如下例所示,以簡化搜尋。 這將搜索限制在字串內的特定範圍內,優化性能和精確度。 以下是操作方法:

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",展示了該方法在大段文字中縮小搜尋範圍的靈活性。

當此程式碼運行時,控制台輸出:

Index of 'text': 7
Index of 'text': 7
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Index @of 'text': 7
$vbLabelText   $csharpLabel

IndexOf 性能考量

雖然 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("Character not found.");
}
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("Character not found.");
}
else
{
    Console.WriteLine("Character found at index: " + index);
}
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("Character not found.")
Else
	Console.WriteLine("Character found at index: " & index)
End If
$vbLabelText   $csharpLabel

當此程式碼運行時,控制台輸出:

Character not found.
Character not found.
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Character @not found.
$vbLabelText   $csharpLabel

處理空字串

另一個特殊情況是當搜尋字串或目標字串為空時。 IndexOf 將任何字串(即使是空字串)的起始視為空子字串的有效位置。 因此,在任何字符串中搜尋空字串都會返回,表示字串的開始。 相反地,在一個空字串內搜尋任何非空的子字串將會返回-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#(對開發人員的工作原理):圖 1 - IronPDF 網頁

IronPDF 是一個為 .NET 框架設計的全面庫,旨在利用 C# 來促進 PDF 文件的創建、編輯和操作。 它以其< a href="/examples/using-html-to-create-a-pdf/">使用 IronPDF 直接從 HTML 生成 PDF、CSS、JavaScript 和圖片的方法脫穎而出,簡化了轉換過程,並確保開發人員可以快速高效地生成文檔。 此程式庫相容於多種類型的 .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 套件管理員輕鬆添加:

Install-Package IronPdf

要在 C# 中整合 IronPDF 的功能與 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 檔案、提取其文字內容,以及在該內容中搜尋特定字串。

當此代碼運行時,控制台輸出:在位置找到的文本:1046

結論

IndexOf C#(它如何為開發人員工作):圖 2 - IronPDF 授權頁面

總結來說,C#的IndexOf方法是程式設計師工具箱中不可或缺的一部分,提供了在字串內有效搜尋字元或子字串的能力。 透過其各種多載,它提供了處理各種文字處理任務所需的靈活性,這使得該方法對開發人員處理字串資料來說不可或缺。 從免費試用 IronPDF開始,然後探索IronPDF 授權選項,價格從$749起。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
C# URL 編碼(開發人員如何操作)
下一個 >
C# 分組(適用於開發者的工作原理)