英語で読む

次の方法で共有


String.IndexOf メソッド

定義

このインスタンス内で最初に出現する指定 Unicode 文字または文字列の 0 から始まるインデックスをレポートします。 このインスタンス内で文字または文字列が見つからない場合、このメソッドは -1 を返します。

オーバーロード

IndexOf(String, Int32, Int32, StringComparison)

指定した文字列が現在の String オブジェクト内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 現在の文字列での検索開始位置、現在の文字列で検索する文字の数、および指定した文字列に使用する検索の種類をパラメーターで指定します。

IndexOf(String, Int32, Int32)

指定された文字列がこのインスタンス内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 検索は指定した文字位置から開始され、指定した数の文字位置が検査されます。

IndexOf(Char, Int32, Int32)

指定文字がこのインスタンス内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 検索は指定した文字位置から開始され、指定した数の文字位置が検査されます。

IndexOf(String, StringComparison)

指定した文字列が現在の String オブジェクト内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 指定した文字列に使用する検索の種類をパラメーターで指定します。

IndexOf(String, Int32, StringComparison)

指定した文字列が現在の String オブジェクト内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 現在の文字列内での検索の開始位置、および指定した文字列に使用する検索の種類をパラメーターで指定します。

IndexOf(Char, StringComparison)

指定した Unicode 文字がこの文字列内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 指定した文字に使用する検索の種類をパラメーターで指定します。

IndexOf(Char, Int32)

指定した Unicode 文字がこの文字列内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 検索は、指定した文字位置から開始されます。

IndexOf(String)

指定された文字列がこのインスタンス内で最初に見つかった位置の 0 から始まるインデックスをレポートします。

IndexOf(Char)

指定した Unicode 文字がこの文字列内で最初に見つかった位置の 0 から始まるインデックスをレポートします。

IndexOf(String, Int32)

指定された文字列がこのインスタンス内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 検索は、指定した文字位置から開始されます。

IndexOf(String, Int32, Int32, StringComparison)

ソース:
String.Searching.cs
ソース:
String.Searching.cs
ソース:
String.Searching.cs

指定した文字列が現在の String オブジェクト内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 現在の文字列での検索開始位置、現在の文字列で検索する文字の数、および指定した文字列に使用する検索の種類をパラメーターで指定します。

C#
public int IndexOf (string value, int startIndex, int count, StringComparison comparisonType);

パラメーター

value
String

シークする文字列。

startIndex
Int32

検索が開始される位置。

count
Int32

検査する文字位置の数。

comparisonType
StringComparison

検索の規則を指定する列挙値の 1 つ。

戻り値

その文字列が見つかった場合は、現在のインスタンスの先頭からの、value パラメーターの 0 から始まるインデックス位置。見つからなかった場合は、-1。 valueEmpty の場合、戻り値は startIndex です。

例外

valuenullです。

count または startIndex が負の値です。

または

startIndex はこのインスタンスの長さを超えています。

または

count がこの文字列の長さ - startIndex より大きいです。

comparisonType は有効な StringComparison 値ではありません。

次の例では、 列挙体の異なる値を IndexOf 使用して、別の文字列内で文字列の最初の出現箇所を検索する メソッドの 3 つのオーバーロードを StringComparison 示します。

C#
// This code example demonstrates the 
// System.String.IndexOf(String, ..., StringComparison) methods.

using System;
using System.Threading;
using System.Globalization;

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the first occurrence of a character using different " + 
                   "values of StringComparison.";
    string resultFmt = "Comparison: {0,-28} Location: {1,3}";

// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
    string CapitalAWithRing = "\u00c5"; 

// Define a string to search. 
// The result of combining the characters LATIN SMALL LETTER A and COMBINING 
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character 
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
    string cat = "A Cheshire c" + "\u0061\u030a" + "t";

    int loc = 0;
    StringComparison[] scValues = {
        StringComparison.CurrentCulture,
        StringComparison.CurrentCultureIgnoreCase,
        StringComparison.InvariantCulture,
        StringComparison.InvariantCultureIgnoreCase,
        StringComparison.Ordinal,
        StringComparison.OrdinalIgnoreCase };

// Clear the screen and display an introduction.
    Console.Clear();
    Console.WriteLine(intro);

// Display the current culture because culture affects the result. For example, 
// try this code example with the "sv-SE" (Swedish-Sweden) culture.

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    Console.WriteLine("The current culture is \"{0}\" - {1}.", 
                       Thread.CurrentThread.CurrentCulture.Name,
                       Thread.CurrentThread.CurrentCulture.DisplayName);

// Display the string to search for and the string to search.
    Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"", 
                       CapitalAWithRing, cat);
    Console.WriteLine();

// Note that in each of the following searches, we look for 
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains 
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates 
// the string was not found.
// Search using different values of StringComparison. Specify the start 
// index and count. 

    Console.WriteLine("Part 1: Start index and count are specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(CapitalAWithRing, 0, cat.Length, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }

// Search using different values of StringComparison. Specify the 
// start index. 
    Console.WriteLine("\nPart 2: Start index is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(CapitalAWithRing, 0, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }

// Search using different values of StringComparison. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(CapitalAWithRing, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }
    }
}

/*
Note: This code example was executed on a console whose user interface 
culture is "en-US" (English-United States).

This code example produces the following results:

Find the first occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

*/

注釈

インデックス番号は 0 (ゼロ) から始まります。 startIndex パラメーターには、0 から文字列インスタンスの長さまでの範囲の値を指定できます。

検索は から startIndex 始まり、-1 に startIndex + count 続きます。 の startIndex + count 文字は検索に含まれません。

パラメーターは comparisonType 、現在のカルチャまたはインバリアント カルチャを使用し、大文字と小文字を区別しない検索または大文字と小文字を区別しない検索を使用し、単語または序数の比較規則を使用して、パラメーターを検索するように指定 value します。

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。これらの文字は、言語またはカルチャに依存した比較を実行する際には考慮されません。 カルチャに依存する検索の場合 (つまり、comparisonTypeOrdinal または OrdinalIgnoreCase でない場合)、value に無視できる文字が含まれていると、その文字を削除して検索した場合と同じ結果になります。 が 1 つ以上の無視可能な文字のみで構成されている場合 valueIndexOf(String, Int32, Int32, StringComparison) メソッドは常に を返 startIndexします。これは、検索が開始される文字位置です。

次の例では、 メソッドを IndexOf(String, Int32, Int32, StringComparison) 使用して、ソフト ハイフン (U+00AD) の位置と、2 つの文字列の 3 番目から 6 番目の文字位置から始まる "m" を検索します。 文字列の 1 つのみに必要な部分文字列が含まれます。 この例が .NET Framework 4 以降で実行されている場合、どちらの場合も、ソフト ハイフンは無視可能な文字であるため、カルチャに依存する比較を実行すると、メソッドは文字列内の "m" のインデックスを返します。 ただし、序数比較を実行すると、最初の文字列でのみ部分文字列が検索されます。 ソフト ハイフンの後に "m" が続く最初の文字列の場合、メソッドはソフト ハイフンのインデックスを返しませんが、カルチャに依存する比較を実行すると、代わりに "m" のインデックスを返します。 このメソッドは、序数に基づく比較を実行したときのみ、最初の文字列に含まれるソフト ハイフンのインデックスを返します。

C#
using System;

public class Example
{
    public static void Main()
    {

        string searchString = "\u00ADm";
        string s1 = "ani\u00ADmal" ;
        string s2 = "animal";

        Console.WriteLine(s1.IndexOf(searchString, 2, 4, StringComparison.CurrentCulture));
        Console.WriteLine(s1.IndexOf(searchString, 2, 4, StringComparison.Ordinal));
        Console.WriteLine(s2.IndexOf(searchString, 2, 4, StringComparison.CurrentCulture));
        Console.WriteLine(s2.IndexOf(searchString, 2, 4, StringComparison.Ordinal));

        // The example displays the following output:
        //       4
        //       3
        //       3
        //       -1
    }
}

適用対象

.NET 9 およびその他のバージョン
製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

IndexOf(String, Int32, Int32)

ソース:
String.Searching.cs
ソース:
String.Searching.cs
ソース:
String.Searching.cs

指定された文字列がこのインスタンス内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 検索は指定した文字位置から開始され、指定した数の文字位置が検査されます。

C#
public int IndexOf (string value, int startIndex, int count);

パラメーター

value
String

シークする文字列。

startIndex
Int32

検索が開始される位置。

count
Int32

検査する文字位置の数。

戻り値

その文字列が見つかった場合は、現在のインスタンスの先頭からの、value の 0 から始まるインデックス位置。見つからなかった場合は、-1。 valueEmpty の場合、戻り値は startIndex です。

例外

valuenullです。

count または startIndex が負の値です。

または

startIndex がこの文字列の長さより大きいです。

または

count がこの文字列の長さ - startIndex より大きいです。

次の例では、別の文字列の部分文字列内の文字列 "he" のすべての出現箇所のインデックスを検索します。 検索の反復ごとに、検索する文字数を再計算する必要があることに注意してください。

C#
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+---";
string br2 = "012345678901234567890123456789012345678901234567890123456789012345678";
string str = "Now is the time for all good men to come to the aid of their country.";
int start;
int at;
int end;
int count;

end = str.Length;
start = end/2;
Console.WriteLine();
Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, end-1);
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The string 'he' occurs at position(s): ");

count = 0;
at = 0;
while((start <= end) && (at > -1))
{
    // start+count must be a position within -str-.
    count = end - start;
    at = str.IndexOf("he", start, count);
    if (at == -1) break;
    Console.Write("{0} ", at);
    start = at+1;
}
Console.WriteLine();

/*
This example produces the following results:

All occurrences of 'he' from position 34 to 68.
0----+----1----+----2----+----3----+----4----+----5----+----6----+---
012345678901234567890123456789012345678901234567890123456789012345678
Now is the time for all good men to come to the aid of their country.

The string 'he' occurs at position(s): 45 56

*/

注釈

インデックス番号は 0 (ゼロ) から始まります。 startIndex パラメーターには、0 から文字列インスタンスの長さまでの範囲の値を指定できます。

このメソッドは、現在のカルチャを使用して単語 (大文字と小文字を区別し、カルチャに依存) 検索を実行します。 検索は から startIndex 始まり、-1 に startIndex + count 続きます。 の startIndex + count 文字は検索に含まれません。

文字セットには無視できる文字が含まれています。これらの文字は、言語またはカルチャに依存した比較を実行する際には考慮されません。 カルチャに依存した検索では、value に無視できる文字が含まれている場合、その文字を削除して検索した場合と同じ結果になります。 が 1 つ以上の無視可能な文字のみで構成されている場合 valueIndexOf(String, Int32, Int32) メソッドは常に を返 startIndexします。これは、検索が開始される文字位置です。 次の例では、 メソッドを IndexOf(String, Int32, Int32) 使用して、ソフト ハイフン (U+00AD) の位置と、2 つの文字列の 3 番目から 6 番目の文字位置から始まる "m" を検索します。 文字列の 1 つのみに必要な部分文字列が含まれます。 この例が .NET Framework 4 以降で実行されている場合、どちらの場合も、ソフト ハイフンは無視可能な文字であるため、カルチャに依存する比較を実行すると、メソッドは文字列内の "m" のインデックスを返します。 "m" の後にソフト ハイフンが含まれる最初の文字列の場合、メソッドはソフト ハイフンのインデックスを返すことができず、代わりに "m" のインデックスを返すことに注意してください。

C#
using System;

public class Example
{
    public static void Main()
    {
        string searchString = "\u00ADm";
        string s1 = "ani\u00ADmal" ;
        string s2 = "animal";

        Console.WriteLine(s1.IndexOf(searchString, 2, 4));
        Console.WriteLine(s2.IndexOf(searchString, 2, 4));

        // The example displays the following output:
        //       4
        //       3
    }
}

注意 (呼び出し元)

「文字列を使用するためのベスト プラクティス」で説明されているように、既定値に代わる文字列比較メソッドを呼び出さないようにし、代わりにパラメーターを明示的に指定する必要があるメソッドを呼び出さないようにすることをお勧めします。 現在のカルチャの比較規則を使用してこの操作を実行するには、そのパラメーターの 値CurrentCultureを 指定して メソッド オーバーロードをIndexOf(String, Int32, Int32, StringComparison)呼び出して、意図をcomparisonType明示的に通知します。 言語対応の比較が必要ない場合は、 の使用を Ordinal検討してください。

こちらもご覧ください

適用対象

.NET 9 およびその他のバージョン
製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

IndexOf(Char, Int32, Int32)

ソース:
String.Searching.cs
ソース:
String.Searching.cs
ソース:
String.Searching.cs

指定文字がこのインスタンス内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 検索は指定した文字位置から開始され、指定した数の文字位置が検査されます。

C#
public int IndexOf (char value, int startIndex, int count);

パラメーター

value
Char

シークする Unicode 文字。

startIndex
Int32

検索が開始される位置。

count
Int32

検査する文字位置の数。

戻り値

その文字が見つかった場合は、文字列の先頭からの、value の 0 から始まるインデックス位置。見つからなかった場合は、-1。

例外

count または startIndex が負の値です。

または

startIndex がこの文字列の長さより大きいです。

または

count がこの文字列の長さ - startIndex より大きいです。

IndexOfメソッドの例を次に示します。

C#
// Example for the String.IndexOf( char, int, int ) method.
using System;

class IndexOfCII 
{
    public static void Main() 
    {
        string br1 = 
            "0----+----1----+----2----+----3----+----" +
            "4----+----5----+----6----+----7";
        string br2 = 
            "0123456789012345678901234567890123456789" +
            "0123456789012345678901234567890";
        string str = 
            "ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi " +
            "ABCDEFGHI abcdefghi ABCDEFGHI";

        Console.WriteLine( 
            "This example of String.IndexOf( char, int, int )\n" +
            "generates the following output." );
        Console.WriteLine( 
            "{0}{1}{0}{2}{0}{3}{0}", 
            Environment.NewLine, br1, br2, str );

        FindAllChar( 'A', str );
        FindAllChar( 'a', str );
        FindAllChar( 'I', str );
        FindAllChar( 'i', str );
        FindAllChar( '@', str );
        FindAllChar( ' ', str );
    }

    static void FindAllChar( Char target, String searched )
    {
        Console.Write( 
            "The character '{0}' occurs at position(s): ", 
            target );

        int     startIndex = -1;
        int     hitCount = 0;

        // Search for all occurrences of the target.
        while( true )
        {
            startIndex = searched.IndexOf( 
                target, startIndex + 1, 
                searched.Length - startIndex - 1 );

            // Exit the loop if the target is not found.
            if( startIndex < 0 )
                break;

            Console.Write( "{0}, ", startIndex );
            hitCount++;
        }

        Console.WriteLine( "occurrences: {0}", hitCount );
    }
}

/*
This example of String.IndexOf( char, int, int )
generates the following output.

0----+----1----+----2----+----3----+----4----+----5----+----6----+----7
01234567890123456789012345678901234567890123456789012345678901234567890
ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI

The character 'A' occurs at position(s): 0, 20, 40, 60, occurrences: 4
The character 'a' occurs at position(s): 10, 30, 50, occurrences: 3
The character 'I' occurs at position(s): 8, 28, 48, 68, occurrences: 4
The character 'i' occurs at position(s): 18, 38, 58, occurrences: 3
The character '@' occurs at position(s): occurrences: 0
The character ' ' occurs at position(s): 9, 19, 29, 39, 49, 59, occurrences: 6
*/

注釈

検索は から startIndex 始まり、-1 に startIndex + count 続きます。 の startIndex + count 文字は検索に含まれません。

インデックス番号は 0 (ゼロ) から始まります。 startIndex パラメーターには、0 から文字列インスタンスの長さまでの範囲の値を指定できます。

このメソッドは序数 (カルチャを区別しない) 検索を実行します。ここで、文字は Unicode スカラー値が同じ場合にのみ、別の文字と同等と見なされます。 カルチャに依存する検索を実行するには、 メソッドを使用します CompareInfo.IndexOf 。ここで、合字 "Æ" (U+00C6) などの事前計算済み文字を表す Unicode スカラー値は、カルチャに応じて 、"AE" (U+0041、U+0045) などの正しいシーケンス内の文字のコンポーネントの出現と同等と見なされる場合があります。

こちらもご覧ください

適用対象

.NET 9 およびその他のバージョン
製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

IndexOf(String, StringComparison)

ソース:
String.Searching.cs
ソース:
String.Searching.cs
ソース:
String.Searching.cs

指定した文字列が現在の String オブジェクト内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 指定した文字列に使用する検索の種類をパラメーターで指定します。

C#
public int IndexOf (string value, StringComparison comparisonType);

パラメーター

value
String

シークする文字列。

comparisonType
StringComparison

検索の規則を指定する列挙値の 1 つ。

戻り値

その文字列が見つかった場合は、value パラメーターのインデックス位置。見つからなかった場合は -1。 valueEmpty の場合、戻り値は 0 です。

例外

valuenullです。

comparisonType は有効な StringComparison 値ではありません。

次の例では、 列挙体の異なる値を IndexOf 使用して、別の文字列内で文字列の最初の出現箇所を検索する メソッドの 3 つのオーバーロードを StringComparison 示します。

C#
// This code example demonstrates the 
// System.String.IndexOf(String, ..., StringComparison) methods.

using System;
using System.Threading;
using System.Globalization;

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the first occurrence of a character using different " + 
                   "values of StringComparison.";
    string resultFmt = "Comparison: {0,-28} Location: {1,3}";

// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
    string CapitalAWithRing = "\u00c5"; 

// Define a string to search. 
// The result of combining the characters LATIN SMALL LETTER A and COMBINING 
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character 
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
    string cat = "A Cheshire c" + "\u0061\u030a" + "t";

    int loc = 0;
    StringComparison[] scValues = {
        StringComparison.CurrentCulture,
        StringComparison.CurrentCultureIgnoreCase,
        StringComparison.InvariantCulture,
        StringComparison.InvariantCultureIgnoreCase,
        StringComparison.Ordinal,
        StringComparison.OrdinalIgnoreCase };

// Clear the screen and display an introduction.
    Console.Clear();
    Console.WriteLine(intro);

// Display the current culture because culture affects the result. For example, 
// try this code example with the "sv-SE" (Swedish-Sweden) culture.

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    Console.WriteLine("The current culture is \"{0}\" - {1}.", 
                       Thread.CurrentThread.CurrentCulture.Name,
                       Thread.CurrentThread.CurrentCulture.DisplayName);

// Display the string to search for and the string to search.
    Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"", 
                       CapitalAWithRing, cat);
    Console.WriteLine();

// Note that in each of the following searches, we look for 
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains 
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates 
// the string was not found.
// Search using different values of StringComparison. Specify the start 
// index and count. 

    Console.WriteLine("Part 1: Start index and count are specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(CapitalAWithRing, 0, cat.Length, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }

// Search using different values of StringComparison. Specify the 
// start index. 
    Console.WriteLine("\nPart 2: Start index is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(CapitalAWithRing, 0, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }

// Search using different values of StringComparison. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(CapitalAWithRing, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }
    }
}

/*
Note: This code example was executed on a console whose user interface 
culture is "en-US" (English-United States).

This code example produces the following results:

Find the first occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

*/

注釈

インデックス番号は 0 から始まります。

パラメーターは comparisonType 、現在のカルチャまたはインバリアント カルチャを使用し、大文字と小文字を区別しない検索または大文字と小文字を区別しない検索を使用し、単語または序数の比較規則を使用して、パラメーターを検索するように指定 value します。

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。これらの文字は、言語またはカルチャに依存した比較を実行する際には考慮されません。 カルチャに依存する検索の場合 (つまり、comparisonTypeOrdinal または OrdinalIgnoreCase でない場合)、value に無視できる文字が含まれていると、その文字を削除して検索した場合と同じ結果になります。 が 1 つ以上の無視可能な文字のみで構成されている場合 valueIndexOf(String, StringComparison) メソッドは常に 0 (ゼロ) を返して、現在のインスタンスの先頭に一致が見つかったことを示します。

次の例では、 メソッドを IndexOf(String, StringComparison) 使用して、3 つの部分文字列 (ソフト ハイフン (U+00AD)、ソフト ハイフンの後に "n"、ソフト ハイフンの後に "m") を 2 つの文字列で検索します。 文字列の 1 つのみにソフト ハイフンが含まれます。 この例が .NET Framework 4 以降で実行されている場合、ソフト ハイフンは無視できる文字であるため、カルチャに依存する検索では、検索文字列にソフト ハイフンが含まれていない場合と同じ値が返されます。 ただし、序数検索では、1 つの文字列でソフト ハイフンが正常に検出され、2 番目の文字列に含まれていないことが報告されます。

C#
using System;

public class Example
{
    public static void Main()
    {
        string s1 = "ani\u00ADmal";
        string s2 = "animal";
      
        Console.WriteLine("Culture-sensitive comparison:");
        // Use culture-sensitive comparison to find the soft hyphen.
        Console.WriteLine(s1.IndexOf("\u00AD", StringComparison.CurrentCulture));
        Console.WriteLine(s2.IndexOf("\u00AD", StringComparison.CurrentCulture));
      
        // Use culture-sensitive comparison to find the soft hyphen followed by "n".
        Console.WriteLine(s1.IndexOf("\u00ADn", StringComparison.CurrentCulture));
        Console.WriteLine(s2.IndexOf("\u00ADn", StringComparison.CurrentCulture));
      
        // Use culture-sensitive comparison to find the soft hyphen followed by "m".
        Console.WriteLine(s1.IndexOf("\u00ADm", StringComparison.CurrentCulture));
        Console.WriteLine(s2.IndexOf("\u00ADm", StringComparison.CurrentCulture));
      
        Console.WriteLine("Ordinal comparison:");
        // Use ordinal comparison to find the soft hyphen.
        Console.WriteLine(s1.IndexOf("\u00AD", StringComparison.Ordinal));
        Console.WriteLine(s2.IndexOf("\u00AD", StringComparison.Ordinal));
      
        // Use ordinal comparison to find the soft hyphen followed by "n".
        Console.WriteLine(s1.IndexOf("\u00ADn", StringComparison.Ordinal));
        Console.WriteLine(s2.IndexOf("\u00ADn", StringComparison.Ordinal));
      
        // Use ordinal comparison to find the soft hyphen followed by "m".
        Console.WriteLine(s1.IndexOf("\u00ADm", StringComparison.Ordinal));
        Console.WriteLine(s2.IndexOf("\u00ADm", StringComparison.Ordinal));

        // The example displays the following output:
        //       Culture-sensitive comparison:
        //       0
        //       0
        //       1
        //       1
        //       4
        //       3
        //       Ordinal comparison:
        //       3
        //       -1
        //       -1
        //       -1
        //       3
        //       -1
    }
}

適用対象

.NET 9 およびその他のバージョン
製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

IndexOf(String, Int32, StringComparison)

ソース:
String.Searching.cs
ソース:
String.Searching.cs
ソース:
String.Searching.cs

指定した文字列が現在の String オブジェクト内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 現在の文字列内での検索の開始位置、および指定した文字列に使用する検索の種類をパラメーターで指定します。

C#
public int IndexOf (string value, int startIndex, StringComparison comparisonType);

パラメーター

value
String

シークする文字列。

startIndex
Int32

検索が開始される位置。

comparisonType
StringComparison

検索の規則を指定する列挙値の 1 つ。

戻り値

その文字列が見つかった場合は、現在のインスタンスの先頭からの、value パラメーターの 0 から始まるインデックス位置。見つからなかった場合は、-1。 valueEmpty の場合、戻り値は startIndex です。

例外

valuenullです。

startIndex が、0 未満か、またはこの文字列の長さを超えています。

comparisonType は有効な StringComparison 値ではありません。

次の例では、 列挙体の異なる値を IndexOf 使用して、別の文字列内で文字列の最初の出現箇所を検索する メソッドの 3 つのオーバーロードを StringComparison 示します。

C#
// This code example demonstrates the 
// System.String.IndexOf(String, ..., StringComparison) methods.

using System;
using System.Threading;
using System.Globalization;

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the first occurrence of a character using different " + 
                   "values of StringComparison.";
    string resultFmt = "Comparison: {0,-28} Location: {1,3}";

// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
    string CapitalAWithRing = "\u00c5"; 

// Define a string to search. 
// The result of combining the characters LATIN SMALL LETTER A and COMBINING 
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character 
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
    string cat = "A Cheshire c" + "\u0061\u030a" + "t";

    int loc = 0;
    StringComparison[] scValues = {
        StringComparison.CurrentCulture,
        StringComparison.CurrentCultureIgnoreCase,
        StringComparison.InvariantCulture,
        StringComparison.InvariantCultureIgnoreCase,
        StringComparison.Ordinal,
        StringComparison.OrdinalIgnoreCase };

// Clear the screen and display an introduction.
    Console.Clear();
    Console.WriteLine(intro);

// Display the current culture because culture affects the result. For example, 
// try this code example with the "sv-SE" (Swedish-Sweden) culture.

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    Console.WriteLine("The current culture is \"{0}\" - {1}.", 
                       Thread.CurrentThread.CurrentCulture.Name,
                       Thread.CurrentThread.CurrentCulture.DisplayName);

// Display the string to search for and the string to search.
    Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"", 
                       CapitalAWithRing, cat);
    Console.WriteLine();

// Note that in each of the following searches, we look for 
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains 
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates 
// the string was not found.
// Search using different values of StringComparison. Specify the start 
// index and count. 

    Console.WriteLine("Part 1: Start index and count are specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(CapitalAWithRing, 0, cat.Length, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }

// Search using different values of StringComparison. Specify the 
// start index. 
    Console.WriteLine("\nPart 2: Start index is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(CapitalAWithRing, 0, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }

// Search using different values of StringComparison. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(CapitalAWithRing, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }
    }
}

/*
Note: This code example was executed on a console whose user interface 
culture is "en-US" (English-United States).

This code example produces the following results:

Find the first occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

*/

注釈

インデックス番号は 0 から始まります。 startIndex パラメーターには、0 から文字列インスタンスの長さまでの範囲の値を指定できます。 が文字列インスタンスの長さに等しい場合 startIndex 、メソッドは -1 を返します。

パラメーターは comparisonType 、現在のカルチャまたはインバリアント カルチャを使用し、大文字と小文字を区別しない検索または大文字と小文字を区別しない検索を使用し、単語または序数の比較規則を使用して、パラメーターを検索するように指定 value します。

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。これらの文字は、言語またはカルチャに依存した比較を実行する際には考慮されません。 カルチャに依存する検索の場合 (つまり、comparisonTypeOrdinal または OrdinalIgnoreCase でない場合)、value に無視できる文字が含まれていると、その文字を削除して検索した場合と同じ結果になります。 が 1 つ以上の無視可能な文字のみで構成されている場合 valueIndexOf(String, Int32, StringComparison) メソッドは常に を返 startIndexします。これは、検索が開始される文字位置です。

次の例では、 メソッドを IndexOf(String, Int32, StringComparison) 使用して、ソフト ハイフン (U+00AD) の位置と、2 つの文字列の 3 番目の文字位置から始まる "m" を検索します。 文字列の 1 つのみに必要な部分文字列が含まれます。 この例が .NET Framework 4 以降で実行されている場合、どちらの場合も、ソフト ハイフンは無視可能な文字であるため、カルチャに依存する比較を実行すると、メソッドは文字列内の "m" のインデックスを返します。 "m" の後にソフト ハイフンが含まれる最初の文字列の場合、メソッドはソフト ハイフンのインデックスを返すことができず、代わりに "m" のインデックスを返すことに注意してください。 このメソッドは、序数に基づく比較を実行したときのみ、最初の文字列に含まれるソフト ハイフンのインデックスを返します。

C#
using System;

public class Example
{
    public static void Main()
    {
      
        string searchString = "\u00ADm";
        string s1 = "ani\u00ADmal" ;
        string s2 = "animal";

        Console.WriteLine(s1.IndexOf(searchString, 2, StringComparison.CurrentCulture));
        Console.WriteLine(s1.IndexOf(searchString, 2, StringComparison.Ordinal));
        Console.WriteLine(s2.IndexOf(searchString, 2, StringComparison.CurrentCulture));
        Console.WriteLine(s2.IndexOf(searchString, 2, StringComparison.Ordinal));

        // The example displays the following output:
        //       4
        //       3
        //       3
        //       -1
    }
}

適用対象

.NET 9 およびその他のバージョン
製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

IndexOf(Char, StringComparison)

ソース:
String.Searching.cs
ソース:
String.Searching.cs
ソース:
String.Searching.cs

指定した Unicode 文字がこの文字列内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 指定した文字に使用する検索の種類をパラメーターで指定します。

C#
public int IndexOf (char value, StringComparison comparisonType);

パラメーター

value
Char

検索対象の文字。

comparisonType
StringComparison

検索の規則を指定する列挙値。

戻り値

その文字が見つかった場合は、value の 0 から始まるインデックスでの位置。見つからなかった場合は -1。

例外

comparisonType は有効な StringComparison 値ではありません。

注釈

インデックス番号は 0 から始まります。

パラメーターはcomparisonTypeStringComparison、引数の検索valueで現在のカルチャまたはインバリアント カルチャを使用するか、大文字と小文字を区別するか、大文字と小文字を区別するか、単語または序数の比較規則を使用するかを指定する列挙メンバーです。

適用対象

.NET 9 およびその他のバージョン
製品 バージョン
.NET Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Standard 2.1

IndexOf(Char, Int32)

ソース:
String.Searching.cs
ソース:
String.Searching.cs
ソース:
String.Searching.cs

指定した Unicode 文字がこの文字列内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 検索は、指定した文字位置から開始されます。

C#
public int IndexOf (char value, int startIndex);

パラメーター

value
Char

シークする Unicode 文字。

startIndex
Int32

検索が開始される位置。

戻り値

その文字が見つかった場合は、文字列の先頭からの、value の 0 から始まるインデックス位置。見つからなかった場合は、-1。

例外

startIndex が、0 (ゼロ) 未満か、または文字列の長さを超えています。

IndexOfメソッドの例を次に示します。

C#
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+---";
string br2 = "012345678901234567890123456789012345678901234567890123456789012345678";
string str = "Now is the time for all good men to come to the aid of their country.";
int start;
int at;

Console.WriteLine();
Console.WriteLine("All occurrences of 't' from position 0 to {0}.", str.Length-1);
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The letter 't' occurs at position(s): ");

at = 0;
start = 0;
while((start < str.Length) && (at > -1))
{
    at = str.IndexOf('t', start);
    if (at == -1) break;
    Console.Write("{0} ", at);
    start = at+1;
}
Console.WriteLine();

/*
This example produces the following results:

All occurrences of 't' from position 0 to 68.
0----+----1----+----2----+----3----+----4----+----5----+----6----+---
012345678901234567890123456789012345678901234567890123456789012345678
Now is the time for all good men to come to the aid of their country.

The letter 't' occurs at position(s): 7 11 33 41 44 55 65

*/

注釈

インデックス番号は 0 から始まります。 startIndex パラメーターには、0 から文字列インスタンスの長さまでの範囲の値を指定できます。 が文字列インスタンスの長さに等しい場合 startIndex 、メソッドは -1 を返します。

検索の範囲は、文字列の末尾まで startIndex です。

このメソッドは序数 (カルチャを区別しない) 検索を実行します。ここで、文字は Unicode スカラー値が同じ場合にのみ、別の文字と同等と見なされます。 カルチャに依存する検索を実行するには、 メソッドを使用します CompareInfo.IndexOf 。ここで、合字 "Æ" (U+00C6) などの事前計算済み文字を表す Unicode スカラー値は、カルチャに応じて 、"AE" (U+0041、U+0045) などの正しいシーケンス内の文字のコンポーネントの出現と同等と見なされる場合があります。

こちらもご覧ください

適用対象

.NET 9 およびその他のバージョン
製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

IndexOf(String)

ソース:
String.Searching.cs
ソース:
String.Searching.cs
ソース:
String.Searching.cs

指定された文字列がこのインスタンス内で最初に見つかった位置の 0 から始まるインデックスをレポートします。

C#
public int IndexOf (string value);

パラメーター

value
String

シークする文字列。

戻り値

その文字列が見つかった場合は、value の 0 から始まるインデックスでの位置。見つからなかった場合は -1。 valueEmpty の場合、戻り値は 0 です。

例外

valuenullです。

次の例では、"animal" で "n" を検索します。 文字列インデックスは 1 つではなく 0 から始まるので、 IndexOf(String) メソッドは "n" が位置 1 にあることを示します。

C#
String str = "animal";
String toFind = "n";
int index = str.IndexOf("n");
Console.WriteLine("Found '{0}' in '{1}' at position {2}",
                toFind, str, index);

// The example displays the following output:
//        Found 'n' in 'animal' at position 1

次の例では、 メソッドを IndexOf 使用して、文内の動物名の開始位置を決定します。 次に、この位置を使用して、動物を記述する形容詞を文に挿入します。

C#
using System;

public class Example {
    public static void Main()
    {
        string animal1 = "fox";
        string animal2 = "dog";

        string strTarget = String.Format("The {0} jumps over the {1}.",
                                         animal1, animal2);

        Console.WriteLine("The original string is:{0}{1}{0}",
                          Environment.NewLine, strTarget);

        Console.Write("Enter an adjective (or group of adjectives) " +
                      "to describe the {0}: ==> ", animal1);
        string adj1 = Console.ReadLine();

        Console.Write("Enter an adjective (or group of adjectives) " +
                      "to describe the {0}: ==> ", animal2);
        string adj2 = Console.ReadLine();

        adj1 = adj1.Trim() + " ";
        adj2 = adj2.Trim() + " ";

        strTarget = strTarget.Insert(strTarget.IndexOf(animal1), adj1);
        strTarget = strTarget.Insert(strTarget.IndexOf(animal2), adj2);

        Console.WriteLine("{0}The final string is:{0}{1}",
                          Environment.NewLine, strTarget);
    }
}
// Output from the example might appear as follows:
//       The original string is:
//       The fox jumps over the dog.
//
//       Enter an adjective (or group of adjectives) to describe the fox: ==> bold
//       Enter an adjective (or group of adjectives) to describe the dog: ==> lazy
//
//       The final string is:
//       The bold fox jumps over the lazy dog.

注釈

インデックス番号は 0 から始まります。

このメソッドは、現在のカルチャを使用して単語 (大文字と小文字を区別し、カルチャに依存) 検索を実行します。 検索は、このインスタンスの最初の文字位置から開始され、最後の文字位置まで続きます。

文字セットには無視できる文字が含まれています。これらの文字は、言語またはカルチャに依存した比較を実行する際には考慮されません。 カルチャに依存した検索では、value に無視できる文字が含まれている場合、その文字を削除して検索した場合と同じ結果になります。 が 1 つ以上の無視可能な文字のみで構成されている場合 valueIndexOf(String) メソッドは常に 0 (ゼロ) を返して、現在のインスタンスの先頭に一致が見つかったことを示します。 次の例では、 メソッドを IndexOf(String) 使用して、3 つの部分文字列 (ソフト ハイフン (U+00AD)、ソフト ハイフンの後に "n"、ソフト ハイフンの後に "m") を 2 つの文字列で検索します。 文字列の 1 つのみにソフト ハイフンが含まれます。 この例が .NET Framework 4 以降で実行されている場合、どちらの場合も、ソフト ハイフンは無視可能な文字であるため、結果はソフト ハイフンが にvalue含まれていない場合と同じです。 ソフト ハイフンのみを検索する場合、メソッドは 0 (ゼロ) を返して、文字列の先頭に一致するものが見つかったことを示します。

C#
using System;

public class Example
{
    public static void Main()
    {
        string s1 = "ani\u00ADmal";
        string s2 = "animal";
      
        // Find the index of the soft hyphen.
        Console.WriteLine(s1.IndexOf("\u00AD"));
        Console.WriteLine(s2.IndexOf("\u00AD"));
      
        // Find the index of the soft hyphen followed by "n".
        Console.WriteLine(s1.IndexOf("\u00ADn"));
        Console.WriteLine(s2.IndexOf("\u00ADn"));
      
        // Find the index of the soft hyphen followed by "m".
        Console.WriteLine(s1.IndexOf("\u00ADm"));
        Console.WriteLine(s2.IndexOf("\u00ADm"));

        // The example displays the following output
        // if run under the .NET Framework 4 or later:
        //       0
        //       0
        //       1
        //       1
        //       4
        //       3
    }
}

注意 (呼び出し元)

「文字列を使用するためのベスト プラクティス」で説明されているように、既定値に代わる文字列比較メソッドを呼び出さないようにし、代わりにパラメーターを明示的に指定する必要があるメソッドを呼び出さないようにすることをお勧めします。 現在のカルチャの比較規則を使用して文字列インスタンス内の部分文字列の最初のインデックスを見つけるには、パラメーターの 値CurrentCultureを 指定して メソッド オーバーロードを呼び出IndexOf(String, StringComparison)すことによって、意図をcomparisonType明示的に通知します。 言語対応の比較が必要ない場合は、 の使用を Ordinal検討してください。

こちらもご覧ください

適用対象

.NET 9 およびその他のバージョン
製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

IndexOf(Char)

ソース:
String.Searching.cs
ソース:
String.Searching.cs
ソース:
String.Searching.cs

指定した Unicode 文字がこの文字列内で最初に見つかった位置の 0 から始まるインデックスをレポートします。

C#
public int IndexOf (char value);

パラメーター

value
Char

シークする Unicode 文字。

戻り値

その文字が見つかった場合は、value の 0 から始まるインデックスでの位置。見つからなかった場合は -1。

次の例では、 メソッドを使用して 文字を検索 String する方法を IndexOf 示します。

C#
// Create a Unicode string with 5 Greek Alpha characters.
String szGreekAlpha = new String('\u0391',5);

// Create a Unicode string with 3 Greek Omega characters.
String szGreekOmega = "\u03A9\u03A9\u03A9";

String szGreekLetters = String.Concat(szGreekOmega, szGreekAlpha, 
                                    szGreekOmega.Clone());

// Display the entire string.
Console.WriteLine("The string: {0}", szGreekLetters);

// The first index of Alpha.
int ialpha = szGreekLetters.IndexOf('\u0391');
// The first index of Omega.
int iomega = szGreekLetters.IndexOf('\u03A9');

Console.WriteLine("First occurrence of the Greek letter Alpha: Index {0}", 
                ialpha);
Console.WriteLine("First occurrence of the Greek letter Omega: Index {0}", 
                iomega);

// The example displays the following output:
//    The string: ΩΩΩΑΑΑΑΑΩΩΩ
//    First occurrence of the Greek letter Alpha: Index 3
//    First occurrence of the Greek letter Omega: Index 0

注釈

インデックス番号は 0 から始まります。

このメソッドは序数 (カルチャを区別しない) 検索を実行します。ここで、文字は Unicode スカラー値が同じ場合にのみ、別の文字と同等と見なされます。 カルチャに依存する検索を実行するには、 メソッドを使用します CompareInfo.IndexOf 。ここで、合字 "Æ" (U+00C6) などの事前計算済み文字を表す Unicode スカラー値は、カルチャに応じて 、"AE" (U+0041、U+0045) などの正しいシーケンス内の文字のコンポーネントの出現と同等と見なされる場合があります。

こちらもご覧ください

適用対象

.NET 9 およびその他のバージョン
製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

IndexOf(String, Int32)

ソース:
String.Searching.cs
ソース:
String.Searching.cs
ソース:
String.Searching.cs

指定された文字列がこのインスタンス内で最初に見つかった位置の 0 から始まるインデックスをレポートします。 検索は、指定した文字位置から開始されます。

C#
public int IndexOf (string value, int startIndex);

パラメーター

value
String

シークする文字列。

startIndex
Int32

検索が開始される位置。

戻り値

その文字列が見つかった場合は、現在のインスタンスの先頭からの、value の 0 から始まるインデックス位置。見つからなかった場合は、-1。 valueEmpty の場合、戻り値は startIndex です。

例外

valuenullです。

startIndex が、0 未満か、またはこの文字列の長さを超えています。

次の例では、ターゲット文字列内の指定した文字列のすべての出現箇所を検索します。

C#
using System;

public class IndexOfTest {
    public static void Main() {

        string strSource = "This is the string which we will perform the search on";

        Console.WriteLine("The search string is:{0}\"{1}\"{0}", Environment.NewLine, strSource);

        string strTarget = "";
        int found = 0;
        int totFinds = 0;

        do {
            Console.Write("Please enter a search value to look for in the above string (hit Enter to exit) ==> ");

            strTarget = Console.ReadLine();

            if (strTarget != "") {

                for (int i = 0; i < strSource.Length; i++) {

                    found = strSource.IndexOf(strTarget, i);

                    if (found >= 0) {
                        totFinds++;
                        i = found;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            else
            {
                return;
            }

            Console.WriteLine("{0}The search parameter '{1}' was found {2} times.{0}",
                    Environment.NewLine, strTarget, totFinds);

            totFinds = 0;
        } while ( true );
    }
}

注釈

インデックス番号は 0 から始まります。 startIndex パラメーターには、0 から文字列インスタンスの長さまでの範囲の値を指定できます。 が文字列インスタンスの長さに等しい場合 startIndex 、メソッドは -1 を返します。

このメソッドは、現在のカルチャを使用して単語 (大文字と小文字を区別し、カルチャに依存) 検索を実行します。 検索は、このインスタンスの startIndex 文字位置から開始され、最後の文字位置まで続きます。

文字セットには無視できる文字が含まれています。これらの文字は、言語またはカルチャに依存した比較を実行する際には考慮されません。 カルチャに依存した検索では、value に無視できる文字が含まれている場合、その文字を削除して検索した場合と同じ結果になります。 が 1 つ以上の無視可能な文字のみで構成されている場合 valueIndexOf(String, Int32) メソッドは常に を返 startIndexします。これは、検索が開始される文字位置です。 次の例では、 メソッドを IndexOf(String, Int32) 使用して、ソフト ハイフン (U+00AD) の後に 2 つの文字列の "m" が続く位置を検索します。 文字列の 1 つのみに必要な部分文字列が含まれます。 この例が .NET Framework 4 以降で実行されている場合、どちらの場合も、ソフト ハイフンは無視できる文字であるため、メソッドは文字列内の "m" のインデックスを返します。 "m" の後にソフト ハイフンが含まれる最初の文字列の場合、メソッドはソフト ハイフンのインデックスを返すことができず、代わりに "m" のインデックスを返すことに注意してください。

C#
using System;

public class Example
{
    public static void Main()
    {
        string searchString = "\u00ADm";
        string s1 = "ani\u00ADmal" ;
        string s2 = "animal";

        Console.WriteLine(s1.IndexOf(searchString, 2));
        Console.WriteLine(s2.IndexOf(searchString, 2));

        // The example displays the following output:
        //       4
        //       3
    }
}

注意 (呼び出し元)

「文字列を使用するためのベスト プラクティス」で説明されているように、既定値に代わる文字列比較メソッドを呼び出さないようにし、代わりにパラメーターを明示的に指定する必要があるメソッドを呼び出さないようにすることをお勧めします。 現在のカルチャの比較規則を使用して、特定の文字位置の後に発生する部分文字列の最初のインデックスを見つけるには、パラメーターの CurrentCulturecomparisonType 値を 使用してメソッド オーバーロードを呼び出IndexOf(String, Int32, StringComparison)すことによって、意図を明示的に通知します。 言語対応の比較が必要ない場合は、 の使用を Ordinal検討してください。

こちらもご覧ください

適用対象

.NET 9 およびその他のバージョン
製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0