String.LastIndexOf メソッド

定義

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

オーバーロード

LastIndexOf(String, Int32, Int32, StringComparison)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。 指定した文字列を検索するときに実行する比較の種類をパラメーターで指定します。

LastIndexOf(String, Int32, StringComparison)

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

LastIndexOf(String, Int32, Int32)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。

LastIndexOf(Char, Int32, Int32)

このインスタンス内の部分文字列で最後に出現する指定 Unicode 文字の 0 から始まるインデックス位置をレポートします。 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。

LastIndexOf(String, Int32)

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

LastIndexOf(Char, Int32)

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

LastIndexOf(String)

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

LastIndexOf(Char)

このインスタンス内で最後に出現する指定 Unicode 文字の 0 から始まるインデックス位置をレポートします。

LastIndexOf(String, StringComparison)

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

LastIndexOf(String, Int32, Int32, StringComparison)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。 指定した文字列を検索するときに実行する比較の種類をパラメーターで指定します。

public:
 int LastIndexOf(System::String ^ value, int startIndex, int count, StringComparison comparisonType);
public int LastIndexOf (string value, int startIndex, int count, StringComparison comparisonType);
member this.LastIndexOf : string * int * int * StringComparison -> int
Public Function LastIndexOf (value As String, startIndex As Integer, count As Integer, comparisonType As StringComparison) As Integer

パラメーター

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 と等しく、start が -1 より小さいか 0 より大きいです。

または

現在のインスタンスが Empty と等しく、count が 1 より大きいです。

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

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

// 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

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

open System
open System.Threading
open System.Globalization

let intro = "Find the last occurrence of a character using different values of StringComparison."

// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let 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).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues = 
    [| StringComparison.CurrentCulture
       StringComparison.CurrentCultureIgnoreCase
       StringComparison.InvariantCulture
       StringComparison.InvariantCultureIgnoreCase
       StringComparison.Ordinal
       StringComparison.OrdinalIgnoreCase  |]

// Clear the screen and display an introduction.
Console.Clear()
printfn $"{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 <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."

// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"

// 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.

printfn "Part 1: Start index and count are specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

(*
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

*)
' This code example demonstrates the 
' System.String.LastIndexOf(String, ..., StringComparison) methods.

Imports System.Threading
Imports System.Globalization

Class Sample
    Public Shared Sub Main() 
        Dim intro As String = "Find the last occurrence of a character using different " & _
                              "values of StringComparison."
        Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
        
        ' Define a string to search for.
        ' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
        Dim CapitalAWithRing As String = "Å"
        
        ' 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).
        Dim cat As String = "A Cheshire c" & "å" & "t"
        Dim loc As Integer = 0
        Dim scValues As StringComparison() =  { _
                        StringComparison.CurrentCulture, _
                        StringComparison.CurrentCultureIgnoreCase, _
                        StringComparison.InvariantCulture, _
                        StringComparison.InvariantCultureIgnoreCase, _
                        StringComparison.Ordinal, _
                        StringComparison.OrdinalIgnoreCase }
        Dim sc As StringComparison
        
        ' 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.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparsion. Specify the 
        ' start index. 
        Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparsion. 
        Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
    
    End Sub
End Class

'
'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開始され、見つかったかvaluecount文字位置が検査されるまで後方に進みます。 たとえば、 が Length - 1 の場合startIndex、メソッドは文字列の最後の文字から後方count文字を検索します。

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

  • 現在または不変のカルチャ。
  • 大文字と小文字を区別する検索または大文字と小文字を区別しない検索。
  • Wordまたは序数の比較規則。

注意 (呼び出し元)

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

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

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
let searchString = "\u00ADm"

let s1 = "ani\u00ADmal"
let s2 = "animal"

let position = s1.LastIndexOf 'm'
if position >= 1 then
    printfn $"{s1.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture)}"
    printfn $"{s1.LastIndexOf(searchString, position, position, StringComparison.Ordinal)}"

let position = s2.LastIndexOf 'm'
if position >= 1 then
    printfn $"{s2.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture)}"
    printfn $"{s2.LastIndexOf(searchString, position, position, StringComparison.Ordinal)}"

// The example displays the following output:
//
// 4
// 3
// 3
// -1
Dim searchString As String = ChrW(&HAD) + "m"

Dim s1 As String = "ani" + ChrW(&HAD) + "m"
Dim s2 As String = "animal"

Dim position As Integer

position = s1.LastIndexOf("m"c)
If position >= 1 Then
    Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture))
    Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.Ordinal))
End If

position = s2.LastIndexOf("m"c)
If position >= 1 Then
    Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture))
    Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.Ordinal))
End If

' The example displays the following output:
'
' 4
' 3
' 3
' -1

適用対象

LastIndexOf(String, Int32, StringComparison)

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

public:
 int LastIndexOf(System::String ^ value, int startIndex, StringComparison comparisonType);
public int LastIndexOf (string value, int startIndex, StringComparison comparisonType);
member this.LastIndexOf : string * int * StringComparison -> int
Public Function LastIndexOf (value As String, startIndex As Integer, comparisonType As StringComparison) As Integer

パラメーター

value
String

シークする文字列。

startIndex
Int32

検索が開始される位置。 検索は、このインスタンスの先頭に向かって startIndex から開始されます。

comparisonType
StringComparison

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

戻り値

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

例外

valuenullです。

現在のインスタンスが Empty と等しくなく、startIndex が 0 未満であるか、または現在のインスタンスの長さを超えています。

または

現在のインスタンスが Empty と等しく、startIndex が -1 未満であるか、または 0 を超えています。

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

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

// 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

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

open System
open System.Threading
open System.Globalization

let intro = "Find the last occurrence of a character using different values of StringComparison."

// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let 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).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues = 
    [| StringComparison.CurrentCulture
       StringComparison.CurrentCultureIgnoreCase
       StringComparison.InvariantCulture
       StringComparison.InvariantCultureIgnoreCase
       StringComparison.Ordinal
       StringComparison.OrdinalIgnoreCase  |]

// Clear the screen and display an introduction.
Console.Clear()
printfn $"{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 <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."

// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"

// 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.

printfn "Part 1: Start index and count are specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

(*
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

*)
' This code example demonstrates the 
' System.String.LastIndexOf(String, ..., StringComparison) methods.

Imports System.Threading
Imports System.Globalization

Class Sample
    Public Shared Sub Main() 
        Dim intro As String = "Find the last occurrence of a character using different " & _
                              "values of StringComparison."
        Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
        
        ' Define a string to search for.
        ' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
        Dim CapitalAWithRing As String = "Å"
        
        ' 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).
        Dim cat As String = "A Cheshire c" & "å" & "t"
        Dim loc As Integer = 0
        Dim scValues As StringComparison() =  { _
                        StringComparison.CurrentCulture, _
                        StringComparison.CurrentCultureIgnoreCase, _
                        StringComparison.InvariantCulture, _
                        StringComparison.InvariantCultureIgnoreCase, _
                        StringComparison.Ordinal, _
                        StringComparison.OrdinalIgnoreCase }
        Dim sc As StringComparison
        
        ' 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.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparsion. Specify the 
        ' start index. 
        Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparsion. 
        Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
    
    End Sub
End Class

'
'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 、最初の文字位置が検査されるまで後方に進みます。 たとえば、 が Length - 1 の場合startIndex、メソッドは文字列の最後の文字から先頭までのすべての文字を検索します。

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

注意 (呼び出し元)

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

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

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
    let searchString = "\u00ADm"

    let s1 = "ani\u00ADmal"
    let s2 = "animal"

    let position = s1.LastIndexOf 'm'
    if position >= 0 then
        printfn $"{s1.LastIndexOf(searchString, position, StringComparison.CurrentCulture)}"
        printfn $"{s1.LastIndexOf(searchString, position, StringComparison.Ordinal)}"

    let position = s2.LastIndexOf 'm'
    if position >= 0 then
        printfn $"{s2.LastIndexOf(searchString, position, StringComparison.CurrentCulture)}"
        printfn $"{s2.LastIndexOf(searchString, position, StringComparison.Ordinal)}"

// The example displays the following output:
//
// 4
// 3
// 3
// -1
Dim searchString As String = ChrW(&HAD) + "m"

Dim s1 As String = "ani" + ChrW(&HAD) + "mal"
Dim s2 As String = "animal"

Dim position As Integer

position = s1.LastIndexOf("m"c)
If position >= 0 Then
    Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.CurrentCulture))
    Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.Ordinal))
End If

position = s2.LastIndexOf("m"c)
If position >= 0 Then
    Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.CurrentCulture))
    Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.Ordinal))
End If

' The example displays the following output:
'
' 4
' 3
' 3
' -1

適用対象

LastIndexOf(String, Int32, Int32)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。

public:
 int LastIndexOf(System::String ^ value, int startIndex, int count);
public int LastIndexOf (string value, int startIndex, int count);
member this.LastIndexOf : string * int * int -> int
Public Function LastIndexOf (value As String, startIndex As Integer, count As Integer) As Integer

パラメーター

value
String

シークする文字列。

startIndex
Int32

検索が開始される位置。 検索は、このインスタンスの先頭に向かって startIndex から開始されます。

count
Int32

検査する文字位置の数。

戻り値

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

例外

valuenullです。

count が負の値です。

または

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

または

現在のインスタンスが Empty と等しくなく、startIndex がこのインスタンスの長さより大きいです。

または

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

または

現在のインスタンスが Empty と等しく、start が -1 より小さいか 0 より大きいです。

または

現在のインスタンスが Empty と等しく、count が 1 より大きいです。

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

// Sample for String::LastIndexOf(String, Int32, Int32)
using namespace System;
int 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
*/
// 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
*/
// Sample for String.LastIndexOf(String, Int32, Int32)
open System

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

let mutable start = str.Length-1
let last = start / 2 - 1
printfn $"All occurrences of 'he' from position {start} to {last}."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The string 'he' occurs at position(s): "

let mutable at = 0
while (start > -1) && (at > -1) do
    let count = start - last //Count must be within the substring.
    at <- str.LastIndexOf("he", start, count)
    if at > -1 then
        printf $"{at} "
        start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{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
*)
' Sample for String.LastIndexOf(String, Int32, Int32)
 _

Class Sample
   
   Public Shared Sub Main()
      
      Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
      Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
      Dim str As String = "Now is the time for all good men to come to the aid of their party."
      Dim start As Integer
      Dim at As Integer
      Dim count As Integer
      Dim [end] As Integer

      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 And at > - 1
         count = start - [end] 'Count must be within the substring.
         at = str.LastIndexOf("he", start, count)
         If at > - 1 Then
            Console.Write("{0} ", at)
            start = at - 1
         End If
      End While
      Console.Write("{0}{0}{0}", Environment.NewLine)
   End Sub
End Class
'
'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始まり、検索が見つかるかcount文字位置が調べられるまでvalue先頭に向かって後方に進みます。 たとえば、 が Length - 1 の場合startIndex、メソッドは文字列の最後の文字から後方count文字を検索します。

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

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

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

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
let s1 = "ani\u00ADmal"
let s2 = "animal"

// Find the index of the soft hyphen followed by "n".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"

if position  >= 0 then
    printfn $"""{s1.LastIndexOf("\u00ADn", position, position + 1)}"""

let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"

if position  >= 0 then
    printfn $"""{s2.LastIndexOf("\u00ADn", position, position + 1)}"""

// Find the index of the soft hyphen followed by "m".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"

if position  >= 0 then
    printfn $"""{s1.LastIndexOf("\u00ADm", position, position + 1)}"""

let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"

if position  >= 0 then
    printfn $"""{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
Dim position As Integer
Dim softHyphen As String = ChrW(&HAD)

Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"

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

If position >= 0 Then
    Console.WriteLine(s1.LastIndexOf(softHyphen + "n", position, position + 1))
End If

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

If position >= 0 Then
    Console.WriteLine(s2.LastIndexOf(softHyphen + "n", position, position + 1))
End If

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

If position >= 0 Then
    Console.WriteLine(s1.LastIndexOf(softHyphen + "m", position, position + 1))
End If

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

If position >= 0 Then
    Console.WriteLine(s2.LastIndexOf(softHyphen + "m", position, position + 1))
End If

' 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

注意 (呼び出し元)

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

こちらもご覧ください

適用対象

LastIndexOf(Char, Int32, Int32)

このインスタンス内の部分文字列で最後に出現する指定 Unicode 文字の 0 から始まるインデックス位置をレポートします。 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。

public:
 int LastIndexOf(char value, int startIndex, int count);
public int LastIndexOf (char value, int startIndex, int count);
member this.LastIndexOf : char * int * int -> int
Public Function LastIndexOf (value As Char, startIndex As Integer, count As Integer) As Integer

パラメーター

value
Char

シークする Unicode 文字。

startIndex
Int32

検索の開始位置。 検索は、このインスタンスの先頭に向かって startIndex から開始されます。

count
Int32

検査する文字位置の数。

戻り値

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

例外

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

または

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

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

// Sample for String::LastIndexOf(Char, Int32, Int32)
using namespace System;
int 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( "\n{0}\n{1}\n{2}", 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;
      }
   }
}

/*
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


*/
// 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


*/
// Sample for String.LastIndexOf(Char, Int32, Int32)
open System

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

let mutable start = str.Length-1
let last = start / 2 - 1
printfn $"All occurrences of 't' from position {start} to {last}."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The letter 't' occurs at position(s): "

let mutable at = 0
while (start > -1) && (at > -1) do
    let count = start - last //Count must be within the substring.
    at <- str.LastIndexOf('t', start, count)
    if at > -1 then
        printf $"{at} "
        start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{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


*)
' Sample for String.LastIndexOf(Char, Int32, Int32)
 _

Class Sample
   
   Public Shared Sub Main()
      
      Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
      Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
      Dim str As String = "Now is the time for all good men to come to the aid of their party."
      Dim start As Integer
      Dim at As Integer
      Dim count As Integer
      Dim [end] As Integer

      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 And at > - 1
         count = start - [end] 'Count must be within the substring.
         at = str.LastIndexOf("t"c, start, count)
         If at > - 1 Then
            Console.Write("{0} ", at)
            start = at - 1
         End If
      End While
      Console.Write("{0}{0}{0}", Environment.NewLine)
   End Sub
End Class
'
'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開始し、見つかったかvaluecount文字位置が調べられるまで、このインスタンスの先頭に向かって後方に進みます。 たとえば、 が Length - 1 の場合startIndex、メソッドは文字列の最後の文字から後方count文字を検索します。 検索では大文字と小文字が区別されます。

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

こちらもご覧ください

適用対象

LastIndexOf(String, Int32)

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

public:
 int LastIndexOf(System::String ^ value, int startIndex);
public int LastIndexOf (string value, int startIndex);
member this.LastIndexOf : string * int -> int
Public Function LastIndexOf (value As String, startIndex As Integer) As Integer

パラメーター

value
String

シークする文字列。

startIndex
Int32

検索が開始される位置。 検索は、このインスタンスの先頭に向かって startIndex から開始されます。

戻り値

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

例外

valuenullです。

現在のインスタンスが Empty と等しくなく、startIndex が 0 未満であるか、または現在のインスタンスの長さを超えています。

または

現在のインスタンスが Empty と等しく、startIndex が -1 未満であるか、または 0 を超えています。

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

// Sample for String::LastIndexOf(String, Int32)
using namespace System;
int 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( "{0}\n{1}\n{2}\n", 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::WriteLine();
}

/*
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
*/
// 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


*/
// Sample for String.LastIndexOf(String, Int32)
open System

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

let mutable start = str.Length - 1
printfn $"All occurrences of 'he' from position {start} to 0." 
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The string 'he' occurs at position(s): "

let mutable at = 0
while (start > -1) && (at > -1) do
    at <- str.LastIndexOf("he", start)
    if at > -1 then
        printf $"{at} "
        start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{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


*)
' Sample for String.LastIndexOf(String, Int32)
 _

Class Sample
   
   Public Shared Sub Main()
      
      Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
      Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
      Dim str As String = "Now is the time for all good men to come to the aid of their party."
      Dim start As Integer
      Dim at As Integer

      '#3
      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 And at > - 1
         at = str.LastIndexOf("he", start)
         If at > - 1 Then
            Console.Write("{0} ", at)
            start = at - 1
         End If
      End While
      Console.Write("{0}{0}{0}", Environment.NewLine)
   End Sub
End Class
'
'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 先頭に向かって進みます。 たとえば、 が Length - 1 の場合startIndex、メソッドは文字列の最後の文字から先頭までのすべての文字を検索します。

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

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

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
let s1 = "ani\u00ADmal"
let s2 = "animal"

// Find the index of the soft hyphen followed by "n".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"

if position >= 0 then
    printfn $"""{s1.LastIndexOf("\u00ADn", position)}"""

let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"

if position >= 0 then
    printfn $"""{s2.LastIndexOf("\u00ADn", position)}"""

// Find the index of the soft hyphen followed by "m".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"

if position >= 0 then
    printfn $"""{s1.LastIndexOf("\u00ADm", position)}"""

let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"

if position >= 0 then
    printfn $"""{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
Dim position As Integer
Dim softHyphen As String = ChrW(&HAD)
Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"

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

If position >= 0 Then
    Console.WriteLine(s1.LastIndexOf(softHyphen + "n", position))
End If

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

If position >= 0 Then
    Console.WriteLine(s2.LastIndexOf(softHyphen + "n", position))
End If

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

If position >= 0 Then
    Console.WriteLine(s1.LastIndexOf(softHyphen + "m", position))
End If

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

If position >= 0 Then
    Console.WriteLine(s2.LastIndexOf(softHyphen + "m", position))
End If

' 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

注意 (呼び出し元)

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

こちらもご覧ください

適用対象

LastIndexOf(Char, Int32)

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

public:
 int LastIndexOf(char value, int startIndex);
public int LastIndexOf (char value, int startIndex);
member this.LastIndexOf : char * int -> int
Public Function LastIndexOf (value As Char, startIndex As Integer) As Integer

パラメーター

value
Char

シークする Unicode 文字。

startIndex
Int32

検索の開始位置。 検索は、このインスタンスの先頭に向かって startIndex から開始されます。

戻り値

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

例外

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

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

// Sample for String::LastIndexOf(Char, Int32)
using namespace System;
int 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( "{0}\n{1}\n{2}\n", 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;
      }
   }
}

/*
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
*/
// 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
*/
// Sample for String.LastIndexOf(Char, Int32)
open System

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

let mutable start = str.Length - 1
printfn $"All occurrences of 't' from position {start} to 0."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The letter 't' occurs at position(s): "

let mutable at = 0
while (start > -1) && (at > -1) do
    at <- str.LastIndexOf('t', start)
    if at > -1 then
        printf $"{at} "
        start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{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
*)
' Sample for String.LastIndexOf(Char, Int32)
Imports System 
 _

Class Sample
   
   Public Shared Sub Main()
      
      Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
      Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
      Dim str As String = "Now is the time for all good men to come to the aid of their party."
      Dim start As Integer
      Dim at As Integer
      
      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 And at > - 1
         at = str.LastIndexOf("t"c, start)
         If at > - 1 Then
            Console.Write("{0} ", at)
            start = at - 1
         End If
      End While
      Console.Write("{0}{0}{0}", Environment.NewLine)
   End Sub
End Class
'
'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 、現在のインスタンスの先頭に向かって後方に進みます。 たとえば、 が Length - 1 の場合startIndex、メソッドは文字列の最後の文字から先頭までのすべての文字を検索します。 検索では大文字と小文字が区別されます。

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

こちらもご覧ください

適用対象

LastIndexOf(String)

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

public:
 int LastIndexOf(System::String ^ value);
public int LastIndexOf (string value);
member this.LastIndexOf : string -> int
Public Function LastIndexOf (value As String) As Integer

パラメーター

value
String

シークする文字列。

戻り値

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

例外

valuenull です。

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

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>
let 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.
for s in strSource do
    printfn $"Before: {s}"
    let mutable item = s
    // Use EndsWith to find a tag at the end of the line.
    if item.Trim().EndsWith ">" then
        // Locate the opening tag.
        let endTagStartPosition = item.LastIndexOf "</"
        // Remove the identified section, if it is valid.
        if endTagStartPosition >= 0 then
            item <- item.Substring(0, endTagStartPosition)

        // Use StartsWith to find the opening tag.
        if item.Trim().StartsWith "<" then
            // Locate the end of opening tab.
            let openTagEndPosition = item.IndexOf ">"
            // Remove the identified section, if it is valid.
            if openTagEndPosition >= 0 then
                item <- item.Substring(openTagEndPosition + 1)
    // Display the trimmed string.
    printfn "After: {item}"
    printfn ""
// 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>
Module Example
   Public Sub Main()
      Dim strSource As String() = { "<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.
      For Each s As String In strSource
         Console.WriteLine("Before: " + s)
         ' Use EndsWith to find a tag at the end of the line.
         If s.Trim().EndsWith(">") Then 
            ' Locate the opening tag.
            Dim endTagStartPosition As Integer = s.LastIndexOf("</")
            ' Remove the identified section if it is valid.
            If endTagStartPosition >= 0 Then
               s = s.Substring(0, endTagStartPosition)
            End If
            
            ' Use StartsWith to find the opening tag.
            If s.Trim().StartsWith("<") Then
               ' Locate the end of opening tab.
               Dim openTagEndPosition As Integer = s.IndexOf(">")
               ' Remove the identified section if it is valid.
               If openTagEndPosition >= 0 Then
                  s = s.Substring(openTagEndPosition + 1)
               End If   
            End If      
         End If
         ' Display the trimmed string.
         Console.WriteLine("After: " + s)
         Console.WriteLine()
      Next                   
   End Sub
End Module
' 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含まれていない場合と同じです。

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
let s1 = "ani\u00ADmal"
let s2 = "animal"

// Find the index of the last soft hyphen followed by "n".
printfn $"""{s1.LastIndexOf "\u00ADn"}"""
printfn $"""{s2.LastIndexOf "\u00ADn"}"""

// Find the index of the last soft hyphen followed by "m".
printfn $"""{s1.LastIndexOf "\u00ADm"}"""
printfn $"""{s2.LastIndexOf "\u00ADm"}"""

// The example displays the following output:
//
// 1
// 1
// 4
// 3
Dim softHyphen As String = ChrW(&HAD)
Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"

' Find the index of the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf(softHyphen + "n"))
Console.WriteLine(s2.LastIndexOf(softHyphen + "n"))

' Find the index of the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf(softHyphen + "m"))
Console.WriteLine(s2.LastIndexOf(softHyphen + "m"))

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

注意 (呼び出し元)

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

こちらもご覧ください

適用対象

LastIndexOf(Char)

このインスタンス内で最後に出現する指定 Unicode 文字の 0 から始まるインデックス位置をレポートします。

public:
 int LastIndexOf(char value);
public int LastIndexOf (char value);
member this.LastIndexOf : char -> int
Public Function LastIndexOf (value As Char) As Integer

パラメーター

value
Char

シークする Unicode 文字。

戻り値

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

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

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;
      }
   }
}
open System
open System.IO

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

do
    let filename = extractFilename @"C:\temp\"
    printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""

    let filename = extractFilename @"C:\temp\delegate.txt"
    printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""

    let filename = extractFilename "delegate.txt"
    printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""

    let filename = extractFilename @"C:\temp\notafile.txt"
    printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""
Imports System.IO

Public Module Test
   Public Sub Main()
      Dim filename As String 
      
      filename = ExtractFilename("C:\temp\")
      Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
      
      filename = ExtractFilename("C:\temp\delegate.txt") 
      Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))

      filename = ExtractFilename("delegate.txt")      
      Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
      
      filename = ExtractFilename("C:\temp\notafile.txt")
      Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
   End Sub
   
   Public Function ExtractFilename(filepath As String) As String
      ' If path ends with a "\", it's a path only so return String.Empty.
      If filepath.Trim().EndsWith("\") Then Return String.Empty
      
      ' Determine where last backslash is.
      Dim position As Integer = filepath.LastIndexOf("\"c)
      ' If there is no backslash, assume that this is a filename.
      If position = -1 Then
         ' Determine whether file exists in the current directory.
         If File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath) Then
            Return filepath
         Else
            Return String.Empty
         End If
      Else
         ' Determine whether file exists using filepath.
         If File.Exists(filepath) Then
            ' Return filename without file path.
            Return filepath.Substring(position + 1)
         Else
            Return String.Empty
         End If                     
      End If
   End Function
End Module 
' The example displays the following output:
'        delegate.txt

注釈

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

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

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

こちらもご覧ください

適用対象

LastIndexOf(String, StringComparison)

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

public:
 int LastIndexOf(System::String ^ value, StringComparison comparisonType);
public int LastIndexOf (string value, StringComparison comparisonType);
member this.LastIndexOf : string * StringComparison -> int
Public Function LastIndexOf (value As String, comparisonType As StringComparison) As Integer

パラメーター

value
String

シークする文字列。

comparisonType
StringComparison

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

戻り値

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

例外

valuenullです。

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

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

// 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

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

open System
open System.Threading
open System.Globalization

let intro = "Find the last occurrence of a character using different values of StringComparison."

// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let 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).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues = 
    [| StringComparison.CurrentCulture
       StringComparison.CurrentCultureIgnoreCase
       StringComparison.InvariantCulture
       StringComparison.InvariantCultureIgnoreCase
       StringComparison.Ordinal
       StringComparison.OrdinalIgnoreCase  |]

// Clear the screen and display an introduction.
Console.Clear()
printfn $"{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 <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."

// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"

// 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.

printfn "Part 1: Start index and count are specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

(*
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

*)
' This code example demonstrates the 
' System.String.LastIndexOf(String, ..., StringComparison) methods.

Imports System.Threading
Imports System.Globalization

Class Sample
    Public Shared Sub Main() 
        Dim intro As String = "Find the last occurrence of a character using different " & _
                              "values of StringComparison."
        Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
        
        ' Define a string to search for.
        ' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
        Dim CapitalAWithRing As String = "Å"
        
        ' 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).
        Dim cat As String = "A Cheshire c" & "å" & "t"
        Dim loc As Integer = 0
        Dim scValues As StringComparison() =  { _
                        StringComparison.CurrentCulture, _
                        StringComparison.CurrentCultureIgnoreCase, _
                        StringComparison.InvariantCulture, _
                        StringComparison.InvariantCultureIgnoreCase, _
                        StringComparison.Ordinal, _
                        StringComparison.OrdinalIgnoreCase }
        Dim sc As StringComparison
        
        ' 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.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparsion. Specify the 
        ' start index. 
        Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparsion. 
        Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
    
    End Sub
End Class

'
'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 検索するように指定します。

  • 現在または不変のカルチャ。
  • 大文字と小文字を区別する検索または大文字と小文字を区別しない検索。
  • Wordまたは序数の比較規則。

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

注意 (呼び出し元)

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

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

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
open System

let s1 = "ani\u00ADmal"
let s2 = "animal"

printfn "Culture-sensitive comparison:"

// Use culture-sensitive comparison to find the last soft hyphen followed by "n".
printfn $"""{s1.LastIndexOf("\u00ADn", StringComparison.CurrentCulture)}"""
printfn $"""{s2.LastIndexOf("\u00ADn", StringComparison.CurrentCulture)}"""

// Use culture-sensitive comparison to find the last soft hyphen followed by "m".
printfn $"""{s1.LastIndexOf("\u00ADm", StringComparison.CurrentCulture)}"""
printfn $"""{s2.LastIndexOf("\u00ADm", StringComparison.CurrentCulture)}"""

printfn "Ordinal comparison:"

// Use ordinal comparison to find the last soft hyphen followed by "n".
printfn $"""{s1.LastIndexOf("\u00ADn", StringComparison.Ordinal)}"""
printfn $"""{s2.LastIndexOf("\u00ADn", StringComparison.Ordinal)}"""

// Use ordinal comparison to find the last soft hyphen followed by "m".
printfn $"""{s1.LastIndexOf("\u00ADm", StringComparison.Ordinal)}"""
printfn $"""{s2.LastIndexOf("\u00ADm", StringComparison.Ordinal)}"""

// The example displays the following output:
//
// Culture-sensitive comparison:
// 1
// 1
// 4
// 3
// Ordinal comparison:
// -1
// -1
// 3
// -1
Dim softHyphen As String = ChrW(&HAD)
Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"

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

' Use culture-sensitive comparison to find the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf(softHyphen + "n", StringComparison.CurrentCulture))
Console.WriteLine(s2.LastIndexOf(softHyphen + "n", StringComparison.CurrentCulture))

' Use culture-sensitive comparison to find the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf(softHyphen + "m", StringComparison.CurrentCulture))
Console.WriteLine(s2.LastIndexOf(softHyphen + "m", StringComparison.CurrentCulture))

Console.WriteLine("Ordinal comparison:")

' Use ordinal comparison to find the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf(softHyphen + "n", StringComparison.Ordinal))
Console.WriteLine(s2.LastIndexOf(softHyphen + "n", StringComparison.Ordinal))

' Use ordinal comparison to find the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf(softHyphen + "m", StringComparison.Ordinal))
Console.WriteLine(s2.LastIndexOf(softHyphen + "m", StringComparison.Ordinal))

' The example displays the following output:
'
' Culture-sensitive comparison:
' 1
' 1
' 4
' 3
' Ordinal comparison:
' -1
' -1
' 3
' -1

適用対象