英語で読む

次の方法で共有


String.LastIndexOf メソッド

定義

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

オーバーロード

LastIndexOf(String, Int32, Int32, StringComparison)

このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は指定した文字位置から開始し、指定した文字数の文字列の先頭に向かって後方に進みます。 パラメーターは、指定した文字列を検索するときに実行する比較の種類を指定します。

LastIndexOf(String, Int32, Int32)

このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は、指定した文字位置から開始し、指定された文字数の文字列の先頭に向かって後方に進みます。

LastIndexOf(Char, Int32, Int32)

指定した Unicode 文字がこのインスタンス内の部分文字列内で最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は、指定した文字位置から開始し、指定された文字数の文字列の先頭に向かって後方に進みます。

LastIndexOf(String, StringComparison)

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

LastIndexOf(String, Int32, StringComparison)

現在の String オブジェクト内で指定した文字列が最後に出現した位置の 0 から始まるインデックスを報告します。 検索は指定した文字位置から開始し、文字列の先頭に向かって後方に進みます。 パラメーターは、指定した文字列を検索するときに実行する比較の種類を指定します。

LastIndexOf(Char, Int32)

指定した Unicode 文字がこのインスタンス内で最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は指定した文字位置から開始し、文字列の先頭に向かって後方に進みます。

LastIndexOf(String)

このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。

LastIndexOf(Char)

指定した Unicode 文字がこのインスタンス内で最後に出現した位置の、0 から始まるインデックス位置を報告します。

LastIndexOf(String, Int32)

このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は指定した文字位置から開始し、文字列の先頭に向かって後方に進みます。

LastIndexOf(String, Int32, Int32, StringComparison)

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

このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は指定した文字位置から開始し、指定した文字数の文字列の先頭に向かって後方に進みます。 パラメーターは、指定した文字列を検索するときに実行する比較の種類を指定します。

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

パラメーター

value
String

シークする文字列。

startIndex
Int32

検索開始位置。 検索は、startIndex からこのインスタンスの先頭に進みます。

count
Int32

調べる文字位置の数。

comparisonType
StringComparison

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

戻り値

その文字列が見つかった場合は、value パラメーターの 0 から始まる開始インデックス位置。見つからない場合、または現在のインスタンスが Empty等しい場合は -1。

例外

valuenullです。

count は負の値です。

-又は-

現在のインスタンスは Empty等しくなく、startIndex は負の値です。

-又は-

現在のインスタンスが Empty等しくなく、startIndex がこのインスタンスの長さを超えています。

-又は-

現在のインスタンスは Emptyと等しくなく、startIndex + 1 - count は、このインスタンス内にない位置を指定します。

-又は-

現在のインスタンスは Empty と等しく、startIndex が -1 未満か、0 より大きい値です。

-又は-

現在のインスタンスは Emptycount は 1 より大きい値です。

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

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

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

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

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the last 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 StringComparsion. Specify the start 
// index and count. 

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

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

// Search using different values of StringComparsion. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.LastIndexOf(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 last 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 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。

検索は startIndex 文字位置から始まり、value が見つかるか、文字位置 count 調べるまで後方に進みます。 たとえば、startIndexLength - 1 の場合、メソッドは文字列の最後の文字から後方 count 文字を検索します。

comparisonType パラメーターは、次を使用して value パラメーターを検索するように指定します。

  • 現在のカルチャまたはインバリアント カルチャ。
  • 大文字と小文字を区別する検索または大文字と小文字を区別しない検索。
  • 単語または序数の比較規則。

注意 (呼び出し元)

文字セットには無視できる文字が含まれます。これは、言語的またはカルチャに依存する比較を実行するときに考慮されない文字です。 カルチャに依存する検索 (つまり、comparisonTypeOrdinal または OrdinalIgnoreCaseでない場合) では、value に無視できる文字が含まれている場合、結果はその文字を削除して検索するのと同じです。

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

C#
string searchString = "\u00ADm";

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

int position;

position = s1.LastIndexOf('m');
if (position >= 1)
{
    Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture));
    Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.Ordinal));
}

position = s2.LastIndexOf('m');
if (position >= 1)
{
    Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture));
    Console.WriteLine(s2.LastIndexOf(searchString, position, position, 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

LastIndexOf(String, Int32, Int32)

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

このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は、指定した文字位置から開始し、指定された文字数の文字列の先頭に向かって後方に進みます。

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

パラメーター

value
String

シークする文字列。

startIndex
Int32

検索開始位置。 検索は、startIndex からこのインスタンスの先頭に進みます。

count
Int32

調べる文字位置の数。

戻り値

その文字列が見つかった場合は、value の 0 から始まる開始インデックス位置。見つからない場合、または現在のインスタンスが Empty等しい場合は -1。

例外

valuenullです。

count は負の値です。

-又は-

現在のインスタンスは Empty等しくなく、startIndex は負の値です。

-又は-

現在のインスタンスが Empty等しくなく、startIndex がこのインスタンスの長さを超えています。

-又は-

現在のインスタンスは Empty等しくなく、startIndex - count+ 1 は、このインスタンス内にない位置を指定します。

-又は-

現在のインスタンスは Empty と等しく、startIndex が -1 未満か、0 より大きい値です。

-又は-

現在のインスタンスは Emptycount は 1 より大きい値です。

次の例では、部分文字列の末尾から部分文字列の先頭まで、文字列のすべての出現箇所のインデックスを検索します。

C#
// Sample for String.LastIndexOf(String, Int32, Int32)
using System;

class Sample {
    public static void Main() {

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

    start = str.Length-1;
    end = start/2 - 1;
    Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, end);
    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 > -1) && (at > -1))
        {
        count = start - end; //Count must be within the substring.
        at = str.LastIndexOf("he", start, count);
        if (at > -1)
            {
            Console.Write("{0} ", at);
            start = at - 1;
            }
        }
    Console.Write("{0}{0}{0}", Environment.NewLine);
    }
}
/*
This example produces the following results:
All occurrences of 'he' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

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

注釈

インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。

検索は、このインスタンスの startIndex 文字位置から始まり、value が見つかるか、文字位置が調べられるまで、先頭 count 戻ります。 たとえば、startIndexLength - 1 の場合、メソッドは文字列の最後の文字から後方 count 文字を検索します。

このメソッドは、現在のカルチャを使用して単語 (大文字と小文字が区別され、カルチャに依存する) 検索を実行します。

文字セットには無視できる文字が含まれます。これは、言語的またはカルチャに依存する比較を実行するときに考慮されない文字です。 カルチャに依存する検索では、value に無視できる文字が含まれている場合、その文字を削除した場合の検索と同じ結果になります。

次の例では、LastIndexOf メソッドを使用して、ソフト ハイフン (U+00AD) の後に 2 つの文字列の "m" または "n" が続く位置を検索します。 ソフト ハイフンを含む文字列は 1 つだけです。 ソフト ハイフンの後に "m" が続く文字列の場合、LastIndexOf は、ソフト ハイフンの後に "m" が続く場合、"m" のインデックスを返します。

C#
int position = 0;
string s1 = "ani\u00ADmal";
string s2 = "animal";

// Find the index of the soft hyphen followed by "n".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s1.LastIndexOf("\u00ADn", position, position + 1));

position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s2.LastIndexOf("\u00ADn", position, position + 1));

// Find the index of the soft hyphen followed by "m".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s1.LastIndexOf("\u00ADm", position, position + 1));

position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s2.LastIndexOf("\u00ADm", position, position + 1));

// The example displays the following output:
//
// 'm' at position 4
// 1
// 'm' at position 3
// 1
// 'm' at position 4
// 4
// 'm' at position 3
// 3

注意 (呼び出し元)

文字列を使用するためのベスト プラクティス で説明したように、既定値に置き換える文字列比較メソッドを呼び出すのではなく、パラメーターを明示的に指定する必要があるメソッドを呼び出さないようにすることをお勧めします。 現在のカルチャの比較規則を使用してこの操作を実行するには、LastIndexOf(String, Int32, Int32, StringComparison) メソッドオーバーロードを呼び出し、その comparisonType パラメーターの値を CurrentCulture して明示的に意図を通知します。 言語に対応した比較が必要ない場合は、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

LastIndexOf(Char, Int32, Int32)

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

指定した Unicode 文字がこのインスタンス内の部分文字列内で最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は、指定した文字位置から開始し、指定された文字数の文字列の先頭に向かって後方に進みます。

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

パラメーター

value
Char

シークする Unicode 文字。

startIndex
Int32

検索の開始位置。 検索は、startIndex からこのインスタンスの先頭に進みます。

count
Int32

調べる文字位置の数。

戻り値

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

例外

現在のインスタンスが Empty等しくなく、startIndex が 0 未満であるか、このインスタンスの長さ以上です。

-又は-

現在のインスタンスは Empty等しくなく、startIndex - count + 1 は 0 未満です。

次の例では、部分文字列の末尾から部分文字列の先頭まで、部分文字列内の文字のすべての出現箇所のインデックスを検索します。

C#
// Sample for String.LastIndexOf(Char, Int32, Int32)
using System;

class Sample {
    public static void Main() {

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

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

    count = 0;
    at = 0;
    while((start > -1) && (at > -1))
        {
        count = start - end; //Count must be within the substring.
        at = str.LastIndexOf('t', start, count);
        if (at > -1)
            {
            Console.Write("{0} ", at);
            start = at - 1;
            }
        }
    Console.Write("{0}{0}{0}", Environment.NewLine);
    }
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

The letter 't' occurs at position(s): 64 55 44 41 33


*/

注釈

インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。

このメソッドは、startIndex 文字位置で検索を開始し、value が見つかるか、count 文字位置が調べられるまで、このインスタンスの先頭に戻ります。 たとえば、startIndexLength - 1 の場合、メソッドは文字列の最後の文字から後方 count 文字を検索します。 検索では大文字と小文字が区別されます。

このメソッドは序数 (カルチャに依存しない) 検索を実行します。この検索では、Unicode スカラー値が同じ場合にのみ、文字が別の文字と同等と見なされます。 カルチャに依存する検索を実行するには、CompareInfo.LastIndexOf メソッドを使用します。ここで、合字 "Æ" (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

LastIndexOf(String, StringComparison)

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

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

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

パラメーター

value
String

シークする文字列。

comparisonType
StringComparison

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

戻り値

その文字列が見つかった場合は、value パラメーターの 0 から始まる開始インデックス位置。見つからない場合は -1。

例外

valuenullです。

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

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

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

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

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the last 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 StringComparsion. Specify the start 
// index and count. 

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

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

// Search using different values of StringComparsion. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.LastIndexOf(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 last 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 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。

comparisonType パラメーターは、次を使用して value パラメーターを検索するように指定します。

  • 現在のカルチャまたはインバリアント カルチャ。
  • 大文字と小文字を区別する検索または大文字と小文字を区別しない検索。
  • 単語または序数の比較規則。

検索は、このインスタンスの最後の文字位置から始まり、value が見つかるか、最初の文字位置が調べられるまで先頭に向かって進みます。

注意 (呼び出し元)

文字セットには無視できる文字が含まれます。これは、言語的またはカルチャに依存する比較を実行するときに考慮されない文字です。 カルチャに依存する検索 (つまり、optionsOrdinal または OrdinalIgnoreCaseでない場合) では、value に無視できる文字が含まれている場合、結果はその文字を削除して検索するのと同じです。

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

C#
string s1 = "ani\u00ADmal";
string s2 = "animal";

Console.WriteLine("Culture-sensitive comparison:");

// Use culture-sensitive comparison to find the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf("\u00ADn", StringComparison.CurrentCulture));
Console.WriteLine(s2.LastIndexOf("\u00ADn", StringComparison.CurrentCulture));

// Use culture-sensitive comparison to find the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf("\u00ADm", StringComparison.CurrentCulture));
Console.WriteLine(s2.LastIndexOf("\u00ADm", StringComparison.CurrentCulture));

Console.WriteLine("Ordinal comparison:");

// Use ordinal comparison to find the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf("\u00ADn", StringComparison.Ordinal));
Console.WriteLine(s2.LastIndexOf("\u00ADn", StringComparison.Ordinal));

// Use ordinal comparison to find the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf("\u00ADm", StringComparison.Ordinal));
Console.WriteLine(s2.LastIndexOf("\u00ADm", StringComparison.Ordinal));

// The example displays the following output:
//
// Culture-sensitive comparison:
// 1
// 1
// 4
// 3
// Ordinal comparison:
// -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

LastIndexOf(String, Int32, StringComparison)

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

現在の String オブジェクト内で指定した文字列が最後に出現した位置の 0 から始まるインデックスを報告します。 検索は指定した文字位置から開始し、文字列の先頭に向かって後方に進みます。 パラメーターは、指定した文字列を検索するときに実行する比較の種類を指定します。

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

パラメーター

value
String

シークする文字列。

startIndex
Int32

検索開始位置。 検索は、startIndex からこのインスタンスの先頭に進みます。

comparisonType
StringComparison

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

戻り値

その文字列が見つかった場合は、value パラメーターの 0 から始まる開始インデックス位置。見つからない場合、または現在のインスタンスが Empty等しい場合は -1。

例外

valuenullです。

現在のインスタンスが Empty等しくなく、startIndex が 0 より小さいか、現在のインスタンスの長さを超えています。

-又は-

現在のインスタンスは Emptyに等しく、startIndex は -1 未満か、0 より大きい値です。

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

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

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

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

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the last 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 StringComparsion. Specify the start 
// index and count. 

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

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

// Search using different values of StringComparsion. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.LastIndexOf(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 last 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 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。

検索は startIndex 文字位置から始まり、value が見つかるか、最初の文字位置が調べられるまで後方に進みます。 たとえば、startIndexLength - 1 の場合、メソッドは文字列の最後の文字から先頭までのすべての文字を検索します。

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

注意 (呼び出し元)

文字セットには無視できる文字が含まれます。これは、言語的またはカルチャに依存する比較を実行するときに考慮されない文字です。 カルチャに依存する検索 (つまり、comparisonTypeOrdinal または OrdinalIgnoreCaseでない場合) では、value に無視できる文字が含まれている場合、結果はその文字を削除して検索するのと同じです。

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

C#
string searchString = "\u00ADm";

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

int position;

position = s1.LastIndexOf('m');
if (position >= 0)
{
    Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.CurrentCulture));
    Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.Ordinal));
}

position = s2.LastIndexOf('m');
if (position >= 0)
{
    Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.CurrentCulture));
    Console.WriteLine(s2.LastIndexOf(searchString, position, 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

LastIndexOf(Char, Int32)

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

指定した Unicode 文字がこのインスタンス内で最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は指定した文字位置から開始し、文字列の先頭に向かって後方に進みます。

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

パラメーター

value
Char

シークする Unicode 文字。

startIndex
Int32

検索の開始位置。 検索は、startIndex からこのインスタンスの先頭に進みます。

戻り値

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

例外

現在のインスタンスが Empty等しくなく、startIndex が 0 未満であるか、このインスタンスの長さ以上です。

次の例では、文字列の末尾から文字列の先頭まで、文字列内のすべての出現箇所のインデックスを検索します。

C#
// Sample for String.LastIndexOf(Char, Int32)
using System;

class Sample {
    public static void Main() {

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

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

    at = 0;
    while((start > -1) && (at > -1))
        {
        at = str.LastIndexOf('t', start);
        if (at > -1)
            {
            Console.Write("{0} ", at);
            start = at - 1;
            }
        }
    Console.Write("{0}{0}{0}", Environment.NewLine);
    }
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

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

注釈

インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。 このメソッドは、このインスタンスの startIndex 文字位置で検索を開始し、value が見つかるか、最初の文字位置が調べられるまで、現在のインスタンスの先頭に戻ります。 たとえば、startIndexLength - 1 の場合、メソッドは文字列の最後の文字から先頭までのすべての文字を検索します。 検索では大文字と小文字が区別されます。

このメソッドは序数 (カルチャに依存しない) 検索を実行します。この検索では、Unicode スカラー値が同じ場合にのみ、文字が別の文字と同等と見なされます。 カルチャに依存する検索を実行するには、CompareInfo.LastIndexOf メソッドを使用します。ここで、合字 "Æ" (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

LastIndexOf(String)

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

このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。

C#
public int LastIndexOf (string value);

パラメーター

value
String

シークする文字列。

戻り値

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

例外

valuenullです。

次の例では、タグが文字列の開始と終了の場合に、文字列から開始と終了の HTML タグを削除します。 文字列が終わり角かっこ (">") で終わる場合、この例では、LastIndexOf メソッドを使用して終了タグの先頭を見つけます。

C#
using System;

public class Example 
{
   public static void Main() 
   {
      string[] strSource = { "<b>This is bold text</b>", "<H1>This is large Text</H1>",
               "<b><i><font color=green>This has multiple tags</font></i></b>",
               "<b>This has <i>embedded</i> tags.</b>",
               "This line ends with a greater than symbol and should not be modified>" };

      // Strip HTML start and end tags from each string if they are present.
      foreach (string s in strSource)
      {
         Console.WriteLine("Before: " + s);
         string item = s;
         // Use EndsWith to find a tag at the end of the line.
         if (item.Trim().EndsWith(">")) 
         {
            // Locate the opening tag.
            int endTagStartPosition = item.LastIndexOf("</");
            // Remove the identified section, if it is valid.
            if (endTagStartPosition >= 0 )
               item = item.Substring(0, endTagStartPosition);

            // Use StartsWith to find the opening tag.
            if (item.Trim().StartsWith("<"))
            {
               // Locate the end of opening tab.
               int openTagEndPosition = item.IndexOf(">");
               // Remove the identified section, if it is valid.
               if (openTagEndPosition >= 0)
                  item = item.Substring(openTagEndPosition + 1);
            }      
         }
         // Display the trimmed string.
         Console.WriteLine("After: " + item);
         Console.WriteLine();
      }                   
   }
}
// The example displays the following output:
//    Before: <b>This is bold text</b>
//    After: This is bold text
//    
//    Before: <H1>This is large Text</H1>
//    After: This is large Text
//    
//    Before: <b><i><font color=green>This has multiple tags</font></i></b>
//    After: <i><font color=green>This has multiple tags</font></i>
//    
//    Before: <b>This has <i>embedded</i> tags.</b>
//    After: This has <i>embedded</i> tags.
//    
//    Before: This line ends with a greater than symbol and should not be modified>
//    After: This line ends with a greater than symbol and should not be modified>

注釈

インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。

検索は、このインスタンスの最後の文字位置から始まり、value が見つかるか、最初の文字位置が調べられるまで先頭に向かって進みます。

このメソッドは、現在のカルチャを使用して単語 (大文字と小文字が区別され、カルチャに依存する) 検索を実行します。

文字セットには無視できる文字が含まれます。これは、言語的またはカルチャに依存する比較を実行するときに考慮されない文字です。 カルチャに依存する検索では、value に無視できる文字が含まれている場合、その文字を削除した場合の検索と同じ結果になります。

次の例では、LastIndexOf(String) メソッドを使用して、2 つの文字列で 2 つの部分文字列 (ソフト ハイフンの後に "n" とソフト ハイフンの後に "m") を検索します。 ソフト ハイフンを含む文字列は 1 つだけです。 この例が .NET Framework 4 以降で実行されている場合、いずれの場合も、ソフト ハイフンは無視できる文字であるため、結果はソフト ハイフンが valueに含まれていない場合と同じです。

C#
string s1 = "ani\u00ADmal";
string s2 = "animal";

// Find the index of the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf("\u00ADn"));
Console.WriteLine(s2.LastIndexOf("\u00ADn"));

// Find the index of the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf("\u00ADm"));
Console.WriteLine(s2.LastIndexOf("\u00ADm"));

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

注意 (呼び出し元)

文字列を使用するためのベスト プラクティス で説明したように、既定値に置き換える文字列比較メソッドを呼び出すのではなく、パラメーターを明示的に指定する必要があるメソッドを呼び出さないようにすることをお勧めします。 現在のカルチャの比較規則を使用して文字列インスタンス内の部分文字列の最後のインデックスを検索するには、LastIndexOf(String, StringComparison) メソッドオーバーロードを呼び出し、その comparisonType パラメーターの値を CurrentCulture して明示的に意図を通知します。 言語に対応した比較が必要ない場合は、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

LastIndexOf(Char)

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

指定した Unicode 文字がこのインスタンス内で最後に出現した位置の、0 から始まるインデックス位置を報告します。

C#
public int LastIndexOf (char value);

パラメーター

value
Char

シークする Unicode 文字。

戻り値

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

次の例では、LastIndexOf(Char) メソッドを使用して文字列内の最後のディレクトリ区切り文字を検索し、文字列のファイル名を抽出する ExtractFilename メソッドを定義します。 ファイルが存在する場合、メソッドはパスのないファイル名を返します。

C#
using System;
using System.IO;

public class TestLastIndexOf
{
   public static void Main()
   {
      string filename;
      
      filename = ExtractFilename(@"C:\temp\");
      Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
      
      filename = ExtractFilename(@"C:\temp\delegate.txt"); 
      Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);

      filename = ExtractFilename("delegate.txt");      
      Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
      
      filename = ExtractFilename(@"C:\temp\notafile.txt");
      Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
   }

   public static string ExtractFilename(string filepath)
   {
      // If path ends with a "\", it's a path only so return String.Empty.
      if (filepath.Trim().EndsWith(@"\"))
         return String.Empty;
      
      // Determine where last backslash is.
      int position = filepath.LastIndexOf('\\');
      // If there is no backslash, assume that this is a filename.
      if (position == -1)
      {
         // Determine whether file exists in the current directory.
         if (File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath)) 
            return filepath;
         else
            return String.Empty;
      }
      else
      {
         // Determine whether file exists using filepath.
         if (File.Exists(filepath))
            // Return filename without file path.
            return filepath.Substring(position + 1);
         else
            return String.Empty;
      }
   }
}

注釈

インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。

このメソッドは、このインスタンスの最後の文字位置で検索を開始し、value が見つかるか、最初の文字位置が調べられるまで先頭に向かって進みます。 検索では大文字と小文字が区別されます。

このメソッドは序数 (カルチャに依存しない) 検索を実行します。この検索では、Unicode スカラー値が同じ場合にのみ、文字が別の文字と同等と見なされます。 カルチャに依存する検索を実行するには、CompareInfo.LastIndexOf メソッドを使用します。ここで、合字 "Æ" (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

LastIndexOf(String, Int32)

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

このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は指定した文字位置から開始し、文字列の先頭に向かって後方に進みます。

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

パラメーター

value
String

シークする文字列。

startIndex
Int32

検索開始位置。 検索は、startIndex からこのインスタンスの先頭に進みます。

戻り値

その文字列が見つかった場合は、value の 0 から始まる開始インデックス位置。見つからない場合、または現在のインスタンスが Empty等しい場合は -1。

例外

valuenullです。

現在のインスタンスが Empty等しくなく、startIndex が 0 より小さいか、現在のインスタンスの長さを超えています。

-又は-

現在のインスタンスは Emptyに等しく、startIndex は -1 未満か、0 より大きい値です。

次の例では、ターゲット文字列内の文字列のすべての出現箇所のインデックスを検索します。これは、ターゲット文字列の末尾からターゲット文字列の先頭まで動作します。

C#
// Sample for String.LastIndexOf(String, Int32)
using System;

class Sample {
    public static void Main() {

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

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

    at = 0;
    while((start > -1) && (at > -1))
        {
        at = str.LastIndexOf("he", start);
        if (at > -1)
            {
            Console.Write("{0} ", at);
            start = at - 1;
            }
        }
    Console.Write("{0}{0}{0}", Environment.NewLine);
    }
}
/*
This example produces the following results:
All occurrences of 'he' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

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


*/

注釈

インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。

検索は、このインスタンスの startIndex 文字位置から始まり、value が見つかるか、最初の文字位置が調べられるまで、先頭に向かって後方に進みます。 たとえば、startIndexLength - 1 の場合、メソッドは文字列の最後の文字から先頭までのすべての文字を検索します。

このメソッドは、現在のカルチャを使用して単語 (大文字と小文字が区別され、カルチャに依存する) 検索を実行します。

文字セットには無視できる文字が含まれます。これは、言語的またはカルチャに依存する比較を実行するときに考慮されない文字です。 カルチャに依存する検索では、value に無視できる文字が含まれている場合、その文字を削除した場合の検索と同じ結果になります。 次の例では、LastIndexOf(String, Int32) メソッドを使用して、ソフト ハイフン (U+00AD) を含み、文字列の最後の "m" の前または末尾に含まれる部分文字列を検索します。 この例が .NET Framework 4 以降で実行されている場合、検索文字列内のソフト ハイフンが無視されるため、メソッドを呼び出してソフト ハイフンで構成される部分文字列を検索し、"m" は文字列内の "m" の位置を返し、それを呼び出してソフト ハイフンで構成される部分文字列を検索し、"n" は "n" の位置を返します。

C#
int position = 0;
string s1 = "ani\u00ADmal";
string s2 = "animal";

// Find the index of the soft hyphen followed by "n".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s1.LastIndexOf("\u00ADn", position));

position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s2.LastIndexOf("\u00ADn", position));

// Find the index of the soft hyphen followed by "m".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s1.LastIndexOf("\u00ADm", position));

position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s2.LastIndexOf("\u00ADm", position));

// The example displays the following output:
//
// 'm' at position 4
// 1
// 'm' at position 3
// 1
// 'm' at position 4
// 4
// 'm' at position 3
// 3

注意 (呼び出し元)

文字列を使用するためのベスト プラクティス で説明したように、既定値に置き換える文字列比較メソッドを呼び出すのではなく、パラメーターを明示的に指定する必要があるメソッドを呼び出さないようにすることをお勧めします。 現在のカルチャの比較規則を使用して、特定の文字位置の前にある部分文字列のインデックスを検索するには、comparisonType パラメーターの値を使用して LastIndexOf(String, Int32, StringComparison) メソッドオーバーロードを呼び出して、意図を明示的に通知 CurrentCulture。 言語に対応した比較が必要ない場合は、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