.NET ヘルプ

IndexOf C#(開発者向けの動作方法)

更新済み 4月 3, 2024
共有:

IndexOfへの入門

C#のIndexOfメソッドは、文字列操作および検索操作で使用される基本的なツールです。 特定の文字またはサブ文字列が別の文字列内のどの位置にあるかを特定するのに役立ちます。 IndexOfの有効性は、指定されたUnicode文字または文字列の最初の出現位置のゼロベースのインデックスを提供する能力にあり、テキストデータの操作における有用性を高めています。

このメソッドは、ユニコード文字を含む個々の文字や文字列を検索することができ、さまざまなプログラミングニーズに対する柔軟性を提供します。 この記事では、IndexOfメソッドの基本について学びます。 IronPDFライブラリ.

基本構文と使用方法

IndexOfの構文

C#の IndexOf の基本構文は非常にシンプルです。 このメソッドにはいくつかのオーバーロードがあり、柔軟な検索パラメーターが可能です。検索の開始点や検査する文字数を指定することができます。

最も単純な形式は public int IndexOf(char value)単一文字を検索する 以下のコードは、特定の値のインデックスを取得するために使用されます: public int IndexOf(文字列値)部分文字列検索用。 高度なバージョンでは、開始インデックスまたは開始インデックスとカウントの両方を指定することができ、検索操作におけるメソッドの柔軟性が向上します。

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
VB   C#

この例に従って、スニペットは文字 '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
VB   C#

インデックスはゼロベースであることに注意してください。つまり、最初の文字はインデックス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)
VB   C#

最初にコードは最初に出現する '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
VB   C#

開始インデックスとカウントを用いた検索

より詳細な検索を行うには、以下の例で示すように、開始インデックスとカウントの両方を指定することで、検索を効率化します。 これは検索を文字列内の特定の範囲に限定し、パフォーマンスと精度を最適化します。 以下のように実行します:

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)
VB   C#

このスニペットは、指定された範囲内で「text」という単語を検索し、大規模な文字列内で検索範囲を絞り込むメソッドの柔軟性を示しています。

このコードを実行すると、コンソールに出力されます:

Index of 'text' : 7
Index of 'text' : 7
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Index @of 'text' : 7
VB   C#

パフォーマンス考慮事項の索引

IndexOf は文字列検索において強力なツールとして際立っていますが、そのデータ構造におけるパフォーマンスへの影響を理解することが重要です。 内部では、IndexOf は線形探索を実行し、開始地点から各文字を確認して、一致するものを見つけるか、検索範囲の終点に到達するまで続けます。

大規模な文字列や複雑な検索、特にUnicode文字を含む場合、これがパフォーマンスに影響を与える可能性があります。 このように、start index(開始位置)およびcount(カウント)パラメータを最適化することにより、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
VB   C#

このコードを実行すると、コンソールに出力されます:

Character not found.
Character not found.
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Character @not found.
VB   C#

空の文字列を処理する

また、検索文字列や対象文字列が空の場合も特別なケースです。 IndexOf は任意の文字列の開始を考慮します。 (空のファイルでさえも) 空のサブストリングの有効な位置として。 したがって、任意の文字列内で空の文字列を検索すると、その文字列の開始位置が示されます。 逆に、空の文字列内で任意の非空の部分文字列を検索すると、可能な一致がないため、-1が返されます。 この動作を理解することは、正確な検索結果を得るために重要です。

ケースの区別と文化的考慮事項

デフォルトでは、IndexOf メソッドは大文字と小文字を区別します。つまり、『a』を検索することと『A』を検索することは異なります。 アプリケーションの要件によっては、大文字小文字を区別しない検索を実行する必要があるかもしれません。 これは、パラメーターとして StringComparison 列挙型を受け取る IndexOf メソッドを使用することで実現できます。 さらに、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
VB   C#

このコードスニペットは、大文字と小文字のバリエーションが文字列内の部分文字列を見つける能力に影響を与えないように、大文字小文字を区別しない検索を実行する方法を示しています。

IronPDF: C# PDFライブラリ

C# の IndexOf (開発者向けの動作方法): 図1 - IronPDFウェブページ

IronPDF .NETフレームワーク向けに設計された包括的なライブラリであり、C#を使用してPDFドキュメントの作成、編集、および操作を容易にします。 そのアプローチで際立っている HTMLから直接PDFを生成CSS、JavaScript、および画像を使用して、変換プロセスを簡素化し、開発者が迅速かつ効率的にドキュメントを作成できるようにします。 このライブラリは、BlazorやWebFormsなどのWebアプリケーション、WPFやMAUIを使用したデスクトップアプリケーションなど、幅広い.NETプロジェクトタイプと互換性があります。 さまざまな開発ニーズに対応するため、Windows、Linux、Mac、およびDockerなどのさまざまな環境やプラットフォームをサポートしています。

コード例

この例を使用するには、プロジェクトに IronPDF がインストールされていることを確認してください。 もしそうでない場合は、以下のコマンドを使用してNuGetパッケージマネージャーで簡単に追加できます:

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
VB   C#

このコードスニペットは、PDFを開き、そのテキストコンテンツを抽出し、そのコンテンツ内で特定の文字列を検索するための基本的なフレームワークを提供します。

このコードを実行すると、コンソールに次のように出力されます: Text found at position: 1046

結論

IndexOf C#(開発者向けの仕組み):図2 - IronPDFのライセンスページ

要約すると、C# の IndexOf メソッドは、文字列内の文字や部分文字列を効率的に検索するため、プログラマーのツールキットの重要な部分です。 さまざまなオーバーロードを通じて、幅広いテキスト処理タスクを扱うために必要な柔軟性を提供し、文字列データを扱う開発者にとって不可欠なメソッドとなっています。 次に、「A」で始まる文章を翻訳します。


Iron Softwareの製品を使用すると、.NET、Java、Python、およびNode.js向けの先進的なPDF操作が可能です。IronPDFを使用すると、開発者は高精度のPDF変換、操作、および生成を実行できます。IronOCRはOCR機能を提供し、スキャンした文書や画像からテキストを抽出するのに役立ちます。IronXLは、Excelファイルの作成、操作、およびエクスポートを便利にします。IronBarcodeは、バーコードの生成と読み取りを容易にします。IronQRは、QRコードの生成と読み取りに特化しています。IronZIPを使えば、ファイルの圧縮と解凍が簡単になります。IronPrintは、プログラムから直接印刷をサポートし、IronWordは、Word文書の操作が簡単にできます。最後に、IronWebScraperはウェブスクレイピングを効率的に実行するためのツールです。

これらの全ての製品は、Iron Suiteとして一つにまとめられており、.NET用のIron Suiteや、無制限の使用が可能なIron Suite Unlimitedなどのライセンスオプションがあります。ライセンスオプションには、Lite License、Plus License、Professional License、Unlimited Licenseがあります。```
 [**無料体験**](trial-license) IronPDFから始めて、$749から始まるライセンスオプションを探ってください。
< 以前
C# URLエンコード(開発者向けの動作方法)
次へ >
C# GroupBy(開発者向けの動作方法)

準備はできましたか? バージョン: 2024.9 新発売

無料のNuGetダウンロード 総ダウンロード数: 10,659,073 View Licenses >