String.LastIndexOf String.LastIndexOf String.LastIndexOf String.LastIndexOf Method

定義

このインスタンス内で最後に出現する指定 Unicode 文字または文字列の 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of a specified Unicode character or string within this instance. このインスタンス内で文字または文字列が見つからない場合、このメソッドは -1 を返します。The method returns -1 if the character or string is not found in this instance.

オーバーロード

LastIndexOf(String, Int32, StringComparison) LastIndexOf(String, Int32, StringComparison) LastIndexOf(String, Int32, StringComparison) LastIndexOf(String, Int32, StringComparison)

指定した文字列が現在の String オブジェクト内で最後に見つかった 0 から始まる位置のインデックスをレポートします。Reports the zero-based index of the last occurrence of a specified string within the current String object. 検索は、指定された文字位置から開始され、文字列の先頭に向かって逆方向に進みます。The search starts at a specified character position and proceeds backward toward the beginning of the string. 指定した文字列を検索するときに実行する比較の種類をパラメーターで指定します。A parameter specifies the type of comparison to perform when searching for the specified string.

LastIndexOf(String, Int32, Int32) LastIndexOf(String, Int32, Int32) LastIndexOf(String, Int32, Int32) LastIndexOf(String, Int32, Int32)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of a specified string within this instance. 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions.

LastIndexOf(Char, Int32, Int32) LastIndexOf(Char, Int32, Int32) LastIndexOf(Char, Int32, Int32) LastIndexOf(Char, Int32, Int32)

このインスタンス内の部分文字列で最後に出現する指定 Unicode 文字の 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of the specified Unicode character in a substring within this instance. 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions.

LastIndexOf(String, StringComparison) LastIndexOf(String, StringComparison) LastIndexOf(String, StringComparison) LastIndexOf(String, StringComparison)

指定した文字列が現在の String オブジェクト内で最後に見つかった 0 から始まる位置のインデックスをレポートします。Reports the zero-based index of the last occurrence of a specified string within the current String object. 指定した文字列に使用する検索の種類をパラメーターで指定します。A parameter specifies the type of search to use for the specified string.

LastIndexOf(Char) LastIndexOf(Char) LastIndexOf(Char) LastIndexOf(Char)

このインスタンス内で最後に出現する指定 Unicode 文字の 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance.

LastIndexOf(Char, Int32) LastIndexOf(Char, Int32) LastIndexOf(Char, Int32) LastIndexOf(Char, Int32)

このインスタンス内で最後に出現する指定 Unicode 文字の 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance. 検索は、指定された文字位置から開始され、文字列の先頭に向かって逆方向に進みます。The search starts at a specified character position and proceeds backward toward the beginning of the string.

LastIndexOf(String) LastIndexOf(String) LastIndexOf(String) LastIndexOf(String)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of a specified string within this instance.

LastIndexOf(String, Int32, Int32, StringComparison) LastIndexOf(String, Int32, Int32, StringComparison) LastIndexOf(String, Int32, Int32, StringComparison) LastIndexOf(String, Int32, Int32, StringComparison)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of a specified string within this instance. 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。The search starts at a specified character position and proceeds backward toward the beginning of the string for the specified number of character positions. 指定した文字列を検索するときに実行する比較の種類をパラメーターで指定します。A parameter specifies the type of comparison to perform when searching for the specified string.

LastIndexOf(String, Int32) LastIndexOf(String, Int32) LastIndexOf(String, Int32) LastIndexOf(String, Int32)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of a specified string within this instance. 検索は、指定された文字位置から開始され、文字列の先頭に向かって逆方向に進みます。The search starts at a specified character position and proceeds backward toward the beginning of the string.

LastIndexOf(String, Int32, StringComparison) LastIndexOf(String, Int32, StringComparison) LastIndexOf(String, Int32, StringComparison) LastIndexOf(String, Int32, StringComparison)

指定した文字列が現在の String オブジェクト内で最後に見つかった 0 から始まる位置のインデックスをレポートします。Reports the zero-based index of the last occurrence of a specified string within the current String object. 検索は、指定された文字位置から開始され、文字列の先頭に向かって逆方向に進みます。The search starts at a specified character position and proceeds backward toward the beginning of the string. 指定した文字列を検索するときに実行する比較の種類をパラメーターで指定します。A parameter specifies the type of comparison to perform when searching for the specified string.

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

シークする文字列。The string to seek.

startIndex
Int32 Int32 Int32 Int32

検索が開始される位置。The search starting position. 検索は、このインスタンスの先頭に向かって startIndex から開始されます。The search proceeds from startIndex toward the beginning of this instance.

comparisonType
StringComparison StringComparison StringComparison StringComparison

検索の規則を指定する列挙値の 1 つ。One of the enumeration values that specifies the rules for the search.

戻り値

その文字列が見つかった場合は、value パラメーターの 0 から始まる開始インデックス位置。見つからなかった場合、または現在のインスタンスが Empty と等しい場合は -1。The zero-based starting index position of the value parameter if that string is found, or -1 if it is not found or if the current instance equals Empty. valueEmpty の場合、戻り値は startIndex かこのインスタンスの最後のインデックス位置のいずれか小さい方です。If value is Empty, the return value is the smaller of startIndex and the last index position in this instance.

例外

現在のインスタンスが Empty と等しくなく、startIndex が 0 未満であるか、または現在のインスタンスの長さを超えています。The current instance does not equal Empty, and startIndex is less than zero or greater than the length of the current instance.

または-or- 現在のインスタンスが Empty と等しく、startIndex が -1 未満であるか、または 0 を超えています。The current instance equals Empty, and startIndex is less than -1 or greater than zero.

comparisonType は有効な StringComparison 値ではありません。comparisonType is not a valid StringComparison value.

次の例では、3 つのオーバー ロード、LastIndexOfのさまざまな値を使用して別の文字列内の文字列の最後の出現箇所を検索するメソッド、StringComparison列挙体。The following example demonstrates three overloads of the LastIndexOf method that find the last occurrence of a string within another string using different values of the StringComparison enumeration.

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

Imports System
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 'Main
End Class 'Sample

'
'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 から開始します。Index numbering starts from zero. つまり、インデックス 0 の文字列の最初の文字は、最後が、 Length - 1。That is, the first character in the string is at index zero and the last is at Length - 1.

検索を開始、startIndex文字の位置および処理されるまで、旧バージョンとの進行状況valueが見つかるまたは最初の文字位置が検査されています。The search begins at the startIndex character position and proceeds backward until either value is found or the first character position has been examined. たとえば場合、startIndexLength- 1、メソッドは、先頭に文字列の最後の文字からのすべての文字を検索します。For example, if startIndex is Length - 1, the method searches every character from the last character in the string to the beginning.

comparisonTypeを検索するパラメーターを指定します、value現在またはインバリアント カルチャを使用して、または区別しない検索を使用して、word または序数比較規則を使用してパラメーター。The comparisonType parameter specifies to search for the value parameter using the current or invariant culture, using a case-sensitive or case-insensitive search, and using word or ordinal comparison rules.

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。これらの文字は、言語またはカルチャに依存した比較を実行する際には考慮されません。Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. カルチャに依存する検索の場合 (つまり、comparisonTypeOrdinal または OrdinalIgnoreCase でない場合)、value に無視できる文字が含まれていると、その文字を削除して検索した場合と同じ結果になります。In a culture-sensitive search (that is, if comparisonType is not Ordinal or OrdinalIgnoreCase), if value contains an ignorable character, the result is equivalent to searching with that character removed. 場合value1 つまたは複数の無視できる文字のみで構成されて、LastIndexOf(String, Int32, StringComparison)メソッドは常に返しますstartIndex、これは、検索の開始文字位置。If value consists only of one or more ignorable characters, the LastIndexOf(String, Int32, StringComparison) method always returns startIndex, which is the character position at which the search begins.

次の例では、 LastIndexOf(String, Int32, StringComparison) "m"、"m"の 2 つの文字列の最後の開始後にソフト ハイフン (U + 00AD) の位置を検索するメソッドを使用します。In the following example, the LastIndexOf(String, Int32, StringComparison) method is used to find the position of a soft hyphen (U+00AD) followed by an "m", starting with the final "m" in two strings. 文字列の 1 つのみに必要な部分文字列が含まれます。Only one of the strings contains the required substring. 例実行している場合、.NET Framework 4.NET Framework 4または後で、どちらの場合も、ソフト ハイフンが、無視できる文字であるため、メソッドのインデックスを返します、文字列内の"m"、カルチャに依存した比較を実行するとき。If the example is run on the .NET Framework 4.NET Framework 4 or later, in both cases, because the soft hyphen is an ignorable character, the method returns the index of "m" in the string when it performs a culture-sensitive comparison. "m" の後にソフト ハイフンが含まれる最初の文字列の場合、メソッドはソフト ハイフンのインデックスを返すことができず、代わりに "m" のインデックスを返すことに注意してください。Note that in the case of the first string, which includes the soft hyphen followed by an "m", the method fails to return the index of the soft hyphen but instead returns the index of the "m". このメソッドは、序数に基づく比較を実行したときのみ、最初の文字列に含まれるソフト ハイフンのインデックスを返します。The method returns the index of the soft hyphen in the first string only when it performs an ordinal comparison.

[!code-csharpSystem.String.LastIndexOf#25] [!code-vbSystem.String.LastIndexOf#25][!code-csharpSystem.String.LastIndexOf#25] [!code-vbSystem.String.LastIndexOf#25]

LastIndexOf(String, Int32, Int32) LastIndexOf(String, Int32, Int32) LastIndexOf(String, Int32, Int32) LastIndexOf(String, Int32, Int32)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of a specified string within this instance. 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions.

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

シークする文字列。The string to seek.

startIndex
Int32 Int32 Int32 Int32

検索が開始される位置。The search starting position. 検索は、このインスタンスの先頭に向かって startIndex から開始されます。The search proceeds from startIndex toward the beginning of this instance.

count
Int32 Int32 Int32 Int32

検査する文字位置の数。The number of character positions to examine.

戻り値

その文字列が見つかった場合は、value の 0 から始まる開始インデックス位置。見つからなかった場合、または現在のインスタンスが Empty と等しい場合は -1。The zero-based starting index position of value if that string is found, or -1 if it is not found or if the current instance equals Empty. valueEmpty の場合、戻り値は startIndex かこのインスタンスの最後のインデックス位置のいずれか小さい方です。If value is Empty, the return value is the smaller of startIndex and the last index position in this instance.

例外

count が負の値です。count is negative.

または-or- 現在のインスタンスが Empty と等しくなく、startIndex が負の値です。The current instance does not equal Empty, and startIndex is negative.

または-or- 現在のインスタンスが Empty と等しくなく、startIndex がこのインスタンスの長さより大きいです。The current instance does not equal Empty, and startIndex is greater than the length of this instance.

または-or- 現在のインスタンスが Empty と等しくなく、startIndex - count + 1 した値がこのインスタンス内にはない位置を指定しています。The current instance does not equal Empty, and startIndex - count+ 1 specifies a position that is not within this instance.

または-or- 現在のインスタンスが Empty と等しく、start が -1 より小さいか 0 より大きいです。The current instance equals Empty and start is less than -1 or greater than zero.

または-or- 現在のインスタンスが Empty と等しく、count が 1 より大きいです。The current instance equals Empty and count is greater than 1.

次の例では、部分文字列を部分文字列の先頭に、部分文字列の末尾からの操作で、文字列のすべての出現箇所のインデックスを検索します。The following example finds the index of all occurrences of a string in substring, working from the end of the substring to the start of the substring.

// 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)
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
      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 'Main 
End Class 'Sample
'
'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 から開始します。Index numbering starts from zero. つまり、インデックス 0 の文字列の最初の文字は、最後が、 Length - 1。That is, the first character in the string is at index zero and the last is at Length - 1.

検索を開始、startIndex文字位置のこのインスタンスと処理が進行するまで先頭に向かって後方valueが見つかるまたはcount文字位置します。The search begins at the startIndex character position of this instance and proceeds backward toward the beginning until either value is found or count character positions have been examined. たとえば場合、startIndexLength- 1、メソッドは逆方向に検索count文字、文字列の最後の文字から。For example, if startIndex is Length - 1, the method searches backward count characters from the last character in the string.

このメソッドは、現在のカルチャを使用して単語 (大文字小文字を区別し、カルチャに依存する) 検索を実行します。This method performs a word (case-sensitive and culture-sensitive) search using the current culture.

文字セットには無視できる文字が含まれています。これらの文字は、言語またはカルチャに依存した比較を実行する際には考慮されません。Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. カルチャに依存した検索では、value に無視できる文字が含まれている場合、その文字を削除して検索した場合と同じ結果になります。In a culture-sensitive search, if value contains an ignorable character, the result is equivalent to searching with that character removed. 場合value1 つまたは複数の無視できる文字のみで構成されて、LastIndexOfメソッドは常に返しますstartIndex、これは、検索の開始文字位置。If value consists only of one or more ignorable characters, the LastIndexOf method always returns startIndex, which is the character position at which the search begins. 次の例では、LastIndexOfメソッドを使用して、2 つの文字の 2 つの文字列の最後の"m"の前にソフト ハイフン (U + 00AD) の位置を調べます。In the following example, the LastIndexOf method is used to find the position of a soft hyphen (U+00AD) in the two characters that precede the final "m" of two strings. 文字列の 1 つのみに必要な部分文字列が含まれます。Only one of the strings contains the required substring. 例実行している場合、.NET Framework 4.NET Framework 4または後で、どちらの場合も、ソフト ハイフンが、無視できる文字であるため、メソッドのインデックスを返します、文字列内の"m"、カルチャに依存した比較を実行するとき。If the example is run on the .NET Framework 4.NET Framework 4 or later, in both cases, because the soft hyphen is an ignorable character, the method returns the index of "m" in the string when it performs a culture-sensitive comparison. "m" の後にソフト ハイフンが含まれる最初の文字列の場合、メソッドはソフト ハイフンのインデックスを返すことができず、代わりに "m" のインデックスを返すことに注意してください。Note that in the case of the first string, which includes the soft hyphen followed by an "m", the method fails to return the index of the soft hyphen but instead returns the index of the "m".

using System;

public class Example
{
   public static void Main()
   {
      int position = 0;
      string s1 = "ani\u00ADmal";
      string s2 = "animal";
      
      // Find the index of the soft hyphen.
      position = s1.LastIndexOf("m");
      Console.WriteLine("'m' at position {0}", position);
      if (position >= 0)
         Console.WriteLine(s1.LastIndexOf("\u00AD", position, position + 1));

      position = s2.LastIndexOf("m");
      Console.WriteLine("'m' at position {0}", position);
      if (position >= 0)   
         Console.WriteLine(s2.LastIndexOf("\u00AD", position, position + 1));
      
      // Find the index of the soft hyphen followed by "n".
      position = s1.LastIndexOf("m");
      Console.WriteLine("'m' at position {0}", position);
      if (position >= 0)
         Console.WriteLine(s1.LastIndexOf("\u00ADn", position, position + 1));

      position = s2.LastIndexOf("m");
      Console.WriteLine("'m' at position {0}", 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 {0}", position);
      if (position >= 0)
         Console.WriteLine(s1.LastIndexOf("\u00ADm", position, position + 1));

      position = s2.LastIndexOf("m");
      Console.WriteLine("'m' at position {0}", position);
      if (position >= 0)   
         Console.WriteLine(s2.LastIndexOf("\u00ADm", position, position + 1));
   }
}
// The example displays the following output:
//       'm' at position 4
//       4
//       'm' at position 3
//       3
//       'm' at position 4
//       1
//       'm' at position 3
//       1
//       'm' at position 4
//       4
//       'm' at position 3
//       3
Module Example
   Public Sub Main()
      Dim position As Integer
      Dim softHyphen As String = ChrW(&h00AD)
      
      Dim s1 As String = "ani" + softHyphen + "mal"
      Dim s2 As String = "animal"
      
      ' Find the index of the soft hyphen.
      position = s1.LastIndexOf("m")
      Console.WriteLine("'m' at position {0}", position)
      If position >= 0 Then
         Console.WriteLine(s1.LastIndexOf(softHyphen, position, position + 1))
      End If
         
      position = s2.LastIndexOf("m")
      Console.WriteLine("'m' at position {0}", position)
      If position >= 0 Then
         Console.WriteLine(s2.LastIndexOf(softHyphen, position, position + 1))
      End If
      
      ' Find the index of the soft hyphen followed by "n".
      position = s1.LastIndexOf("m")
      Console.WriteLine("'m' at position {0}", 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 {0}", 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 {0}", 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 {0}", position)
      If position >= 0 Then
         Console.WriteLine(s2.LastIndexOf(softHyphen + "m", position, position + 1))
      End If
   End Sub
End Module
' The example displays the following output:
'       'm' at position 4
'       4
'       'm' at position 3
'       3
'       'm' at position 4
'       1
'       'm' at position 3
'       1
'       'm' at position 4
'       4
'       'm' at position 3
'       3

注意 (呼び出し元)

説明したよう文字列を使用するためのベスト プラクティス既定値を代入しを明示的に指定するパラメーターを必要とするメソッドを呼び出す代わりに文字列比較メソッドを呼び出さないようにすることをお勧めします。As explained in Best Practices for Using Strings, we recommend that you avoid calling string comparison methods that substitute default values and instead call methods that require parameters to be explicitly specified. 現在のカルチャの比較規則を使用して、この操作を実行する、LastIndexOf(String, Int32, Int32, StringComparison)メソッドのオーバー ロードの値を持つCurrentCulturecomparisonTypeパラメーター。To perform this operation by using the comparison rules of the current culture, call the LastIndexOf(String, Int32, Int32, StringComparison) method overload with a value of CurrentCulture for its comparisonType parameter.

こちらもご覧ください

LastIndexOf(Char, Int32, Int32) LastIndexOf(Char, Int32, Int32) LastIndexOf(Char, Int32, Int32) LastIndexOf(Char, Int32, Int32)

このインスタンス内の部分文字列で最後に出現する指定 Unicode 文字の 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of the specified Unicode character in a substring within this instance. 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。The search starts at a specified character position and proceeds backward toward the beginning of the string for a specified number of character positions.

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

シークする Unicode 文字。The Unicode character to seek.

startIndex
Int32 Int32 Int32 Int32

検索の開始位置。The starting position of the search. 検索は、このインスタンスの先頭に向かって startIndex から開始されます。The search proceeds from startIndex toward the beginning of this instance.

count
Int32 Int32 Int32 Int32

検査する文字位置の数。The number of character positions to examine.

戻り値

その文字が見つかった場合は、value の 0 から始まるインデックス位置。見つからなかった場合、または現在のインスタンスが Empty と等しい場合は -1。The zero-based index position of value if that character is found, or -1 if it is not found or if the current instance equals Empty.

例外

現在のインスタンスが Empty と等しくなく、startIndex が 0 未満であるか、このインスタンスの長さ以上です。The current instance does not equal Empty, and startIndex is less than zero or greater than or equal to the length of this instance.

または-or- 現在のインスタンスが Empty と等しくなく、startIndex - count + 1 が 0 未満です。The current instance does not equal Empty, and startIndex - count + 1 is less than zero.

次の例では、部分文字列の先頭に、部分文字列の末尾から作業の部分文字列内で出現するすべての文字のインデックスを検索します。The following example finds the index of all occurrences of a character in a substring, working from the end of the substring to the start of the substring.

// 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)
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
      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 'Main 
End Class 'Sample
'
'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 から開始します。Index numbering starts from zero. つまり、インデックス 0 の文字列の最初の文字は、最後が、 Length - 1。That is, the first character in the string is at index zero and the last is at Length - 1.

このメソッドでの検索を開始、startIndex文字位置が続行されるまで、このインスタンスの先頭に向かって後方valueが見つかるまたはcount文字位置します。This method begins searching at the startIndex character position and proceeds backward toward the beginning of this instance until either value is found or count character positions have been examined. たとえば場合、startIndexLength- 1、メソッドは逆方向に検索count文字、文字列の最後の文字から。For example, if startIndex is Length - 1, the method searches backward count characters from the last character in the string. 検索は大文字小文字が区別されます。The search is case-sensitive.

このメソッドは、場所文字と見なされますを別の文字と等価の Unicode スカラー値が同じ場合にのみ、序数 (カルチャに依存しない) 検索を実行します。This method performs an ordinal (culture-insensitive) search, where a character is considered equivalent to another character only if their Unicode scalar value are the same. カルチャに依存する検索を実行するには、使用、CompareInfo.LastIndexOfメソッド、場所、構成済みの文字を表す、合字「Æ」など (U + 00 C 6)、Unicode スカラー値可能性がありますに相当する文字の構成要素の出現、"AE"などのシーケンスを修正 (u+0041、u+0045)、カルチャによって異なります。To perform a culture-sensitive search, use the CompareInfo.LastIndexOf method, where a Unicode scalar value representing a precomposed character, such as the ligature "Æ" (U+00C6), might be considered equivalent to any occurrence of the character's components in the correct sequence, such as "AE" (U+0041, U+0045), depending on the culture.

こちらもご覧ください

LastIndexOf(String, StringComparison) LastIndexOf(String, StringComparison) LastIndexOf(String, StringComparison) LastIndexOf(String, StringComparison)

指定した文字列が現在の String オブジェクト内で最後に見つかった 0 から始まる位置のインデックスをレポートします。Reports the zero-based index of the last occurrence of a specified string within the current String object. 指定した文字列に使用する検索の種類をパラメーターで指定します。A parameter specifies the type of search to use for the specified string.

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

シークする文字列。The string to seek.

comparisonType
StringComparison StringComparison StringComparison StringComparison

検索の規則を指定する列挙値の 1 つ。One of the enumeration values that specifies the rules for the search.

戻り値

その文字列が見つかった場合は、value パラメーターの 0 から始まる開始インデックス位置。見つからなかった場合は -1。The zero-based starting index position of the value parameter if that string is found, or -1 if it is not. valueEmpty の場合、戻り値はこのインスタンスの最後のインデックス位置です。If value is Empty, the return value is the last index position in this instance.

例外

comparisonType は有効な StringComparison 値ではありません。comparisonType is not a valid StringComparison value.

次の例では、3 つのオーバー ロード、LastIndexOfのさまざまな値を使用して別の文字列内の文字列の最後の出現箇所を検索するメソッド、StringComparison列挙体。The following example demonstrates three overloads of the LastIndexOf method that find the last occurrence of a string within another string using different values of the StringComparison enumeration.

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

Imports System
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 'Main
End Class 'Sample

'
'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 から開始します。Index numbering starts from zero. つまり、インデックス 0 の文字列の最初の文字は、最後が、 Length - 1。That is, the first character in the string is at index zero and the last is at Length - 1.

comparisonTypeを検索するパラメーターを指定します、value現在またはインバリアント カルチャを使用して、または区別しない検索を使用して、word または序数比較規則を使用してパラメーター。The comparisonType parameter specifies to search for the value parameter using the current or invariant culture, using a case-sensitive or case-insensitive search, and using word or ordinal comparison rules.

検索は、このインスタンスの最後の文字位置から開始し、されるまで、先頭に向かって逆valueが見つかるまたは最初の文字位置が検査されています。The search begins at the last character position of this instance and proceeds backward toward the beginning until either value is found or the first character position has been examined.

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。これらの文字は、言語またはカルチャに依存した比較を実行する際には考慮されません。Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. カルチャに依存する検索の場合 (つまり、optionsOrdinal または OrdinalIgnoreCase でない場合)、value に無視できる文字が含まれていると、その文字を削除して検索した場合と同じ結果になります。In a culture-sensitive search (that is, if options is not Ordinal or OrdinalIgnoreCase), if value contains an ignorable character, the result is equivalent to searching with that character removed. 場合value1 つまたは複数の無視できる文字のみで構成されて、LastIndexOf(String, StringComparison)メソッドは常に返しますLength-1 で、現在のインスタンス内の最後のインデックス位置を表します。If value consists only of one or more ignorable characters, the LastIndexOf(String, StringComparison) method always returns Length - 1, which represents the last index position in the current instance.

次の例では、LastIndexOf(String, StringComparison)メソッドを使用して、2 つの文字列 (ソフト ハイフン (U + 00AD)、"n"の後にソフト ハイフンおよびソフト ハイフン、および"m") の 3 つの部分文字列を検索します。In the following example, the LastIndexOf(String, StringComparison) method is used to find three substrings (a soft hyphen (U+00AD), a soft hyphen followed by "n", and a soft hyphen followed by "m") in two strings. 文字列の 1 つのみにソフト ハイフンが含まれます。Only one of the strings contains a soft hyphen. 例実行している場合、.NET Framework 4.NET Framework 4後、ソフト ハイフンが無視できる文字であるため、カルチャに依存する検索値を返します同じ検索文字列にソフト ハイフンが含まれていないかどうかを返すことができます。If the example is run on the .NET Framework 4.NET Framework 4 or later, because the soft hyphen is an ignorable character, a culture-sensitive search returns the same value that it would return if the soft hyphen were not included in the search string. ただし、序数に基づく検索は、正常に 1 つの文字列でソフト ハイフンを検索して、それが存在しないことを報告 2 番目の文字列から。An ordinal search, however, successfully finds the soft hyphen in one string and reports that it is absent from the second string.

[!code-csharpSystem.String.LastIndexOf#26] [!code-vbSystem.String.LastIndexOf#26][!code-csharpSystem.String.LastIndexOf#26] [!code-vbSystem.String.LastIndexOf#26]

LastIndexOf(Char) LastIndexOf(Char) LastIndexOf(Char) LastIndexOf(Char)

このインスタンス内で最後に出現する指定 Unicode 文字の 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance.

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

シークする Unicode 文字。The Unicode character to seek.

戻り値

その文字が見つかった場合は、value の 0 から始まるインデックスでの位置。見つからなかった場合は -1。The zero-based index position of value if that character is found, or -1 if it is not.

次の例では、定義、ExtractFilenameメソッドを使用する、LastIndexOf(Char)メソッド、文字列内の最後のディレクトリの区切り記号を検索し、文字列のファイル名を抽出します。The following example defines an ExtractFilename method that uses the LastIndexOf(Char) method to find the last directory separator character in a string and to extract the string's file name. ファイルが存在する場合は、パスを除いたファイル名を返します。If the file exists, the method returns the file name without its path.

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;
      }
   }
}
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 から開始します。Index numbering starts from zero. つまり、インデックス 0 の文字列の最初の文字は、最後が、 Length - 1。That is, the first character in the string is at index zero and the last is at Length - 1.

このメソッドは、このインスタンスの最後の文字位置から検索を開始し、されるまで、先頭に向かって逆valueが見つかるまたは最初の文字位置が検査されています。This method begins searching at the last character position of this instance and proceeds backward toward the beginning until either value is found or the first character position has been examined. 検索は大文字小文字が区別されます。The search is case-sensitive.

このメソッドは、場所文字と見なされますを別の文字と等価の Unicode スカラー値が同じ場合にのみ、序数 (カルチャに依存しない) 検索を実行します。This method performs an ordinal (culture-insensitive) search, where a character is considered equivalent to another character only if their Unicode scalar values are the same. カルチャに依存する検索を実行するには、使用、CompareInfo.LastIndexOfメソッド、場所、構成済みの文字を表す、合字「Æ」など (U + 00 C 6)、Unicode スカラー値可能性がありますに相当する文字の構成要素の出現、"AE"などのシーケンスを修正 (u+0041、u+0045)、カルチャによって異なります。To perform a culture-sensitive search, use the CompareInfo.LastIndexOf method, where a Unicode scalar value representing a precomposed character, such as the ligature "Æ" (U+00C6), might be considered equivalent to any occurrence of the character's components in the correct sequence, such as "AE" (U+0041, U+0045), depending on the culture.

こちらもご覧ください

LastIndexOf(Char, Int32) LastIndexOf(Char, Int32) LastIndexOf(Char, Int32) LastIndexOf(Char, Int32)

このインスタンス内で最後に出現する指定 Unicode 文字の 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance. 検索は、指定された文字位置から開始され、文字列の先頭に向かって逆方向に進みます。The search starts at a specified character position and proceeds backward toward the beginning of the string.

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

シークする Unicode 文字。The Unicode character to seek.

startIndex
Int32 Int32 Int32 Int32

検索の開始位置。The starting position of the search. 検索は、このインスタンスの先頭に向かって startIndex から開始されます。The search proceeds from startIndex toward the beginning of this instance.

戻り値

その文字が見つかった場合は、value の 0 から始まるインデックス位置。見つからなかった場合、または現在のインスタンスが Empty と等しい場合は -1。The zero-based index position of value if that character is found, or -1 if it is not found or if the current instance equals Empty.

例外

現在のインスタンスが Empty と等しくなく、startIndex が 0 未満であるか、このインスタンスの長さ以上です。The current instance does not equal Empty, and startIndex is less than zero or greater than or equal to the length of this instance.

次の例では、文字列、文字列の先頭に、文字列の末尾から作業に出現するすべての文字のインデックスを検索します。The following example finds the index of all occurrences of a character in a string, working from the end of the string to the start of the string.

// 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)
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 'Main
End Class 'Sample
'
'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 から開始します。Index numbering starts from zero. つまり、インデックス 0 の文字列の最初の文字は、最後が、 Length -1. このメソッドの開始に検索、startIndex文字位置のこのインスタンスと処理されるまで、現在のインスタンスの先頭に向かって後方の進行状況valueが見つかるまたは最初の文字位置が検査されています。That is, the first character in the string is at index zero and the last is at Length - 1.This method begins searching at the startIndex character position of this instance and proceeds backward toward the beginning of the current instance until either value is found or the first character position has been examined. たとえば場合、startIndexLength- 1、メソッドは、先頭に文字列の最後の文字からのすべての文字を検索します。For example, if startIndex is Length - 1, the method searches every character from the last character in the string to the beginning. 検索は大文字小文字が区別されます。The search is case-sensitive.

このメソッドは、場所文字と見なされますを別の文字と等価の Unicode スカラー値が同じ場合にのみ、序数 (カルチャに依存しない) 検索を実行します。This method performs an ordinal (culture-insensitive) search, where a character is considered equivalent to another character only if their Unicode scalar values are the same. カルチャに依存する検索を実行するには、使用、CompareInfo.LastIndexOfメソッド、場所、構成済みの文字を表す、合字「Æ」など (U + 00 C 6)、Unicode スカラー値可能性がありますに相当する文字の構成要素の出現、"AE"などのシーケンスを修正 (u+0041、u+0045)、カルチャによって異なります。To perform a culture-sensitive search, use the CompareInfo.LastIndexOf method, where a Unicode scalar value representing a precomposed character, such as the ligature "Æ" (U+00C6), might be considered equivalent to any occurrence of the character's components in the correct sequence, such as "AE" (U+0041, U+0045), depending on the culture.

こちらもご覧ください

LastIndexOf(String) LastIndexOf(String) LastIndexOf(String) LastIndexOf(String)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of a specified string within this instance.

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

シークする文字列。The string to seek.

戻り値

その文字列が見つかった場合は、value の 0 から始まる開始インデックス位置。見つからなかった場合は -1。The zero-based starting index position of value if that string is found, or -1 if it is not. valueEmpty の場合、戻り値はこのインスタンスの最後のインデックス位置です。If value is Empty, the return value is the last index position in this instance.

例外

次の例では、タグと終了タグで開始する場合、文字列および文字列の末尾から HTML タグを削除します。The following example removes opening and closing HTML tags from a string if the tags begin and end the string. 場合は、文字列で終わる終了角かっこ文字 (">")、例では、LastIndexOf終了タグの開始を検索するメソッド。If a string ends with a closing bracket character (">"), the example uses the LastIndexOf method to locate the start of the end tag.

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>
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 から開始します。Index numbering starts from zero. つまり、インデックス 0 の文字列の最初の文字は、最後が、 Length - 1。That is, the first character in the string is at index zero and the last is at Length - 1.

検索は、このインスタンスの最後の文字位置から開始し、されるまで、先頭に向かって逆valueが見つかるまたは最初の文字位置が検査されています。The search begins at the last character position of this instance and proceeds backward toward the beginning until either value is found or the first character position has been examined.

このメソッドは、現在のカルチャを使用して単語 (大文字小文字を区別し、カルチャに依存する) 検索を実行します。This method performs a word (case-sensitive and culture-sensitive) search using the current culture.

文字セットには無視できる文字が含まれています。これらの文字は、言語またはカルチャに依存した比較を実行する際には考慮されません。Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. カルチャに依存した検索では、value に無視できる文字が含まれている場合、その文字を削除して検索した場合と同じ結果になります。In a culture-sensitive search, if value contains an ignorable character, the result is equivalent to searching with that character removed. 場合value1 つまたは複数の無視できる文字のみで構成されて、LastIndexOf(String)メソッドは常に返しますString.Length-1 で、現在のインスタンス内の最後のインデックス位置を表します。If value consists only of one or more ignorable characters, the LastIndexOf(String) method always returns String.Length - 1, which represents the last index position in the current instance. 次の例では、LastIndexOf(String)メソッドを使用して、2 つの文字列 (ソフト ハイフン (U + 00AD)、"n"の後にソフト ハイフンおよびソフト ハイフン、および"m") の 3 つの部分文字列を検索します。In the following example, the LastIndexOf(String) method is used to find three substrings (a soft hyphen (U+00AD), a soft hyphen followed by "n", and a soft hyphen followed by "m") in two strings. 文字列の 1 つのみにソフト ハイフンが含まれます。Only one of the strings contains a soft hyphen. 例実行している場合、.NET Framework 4.NET Framework 4後で、各ケースでソフト ハイフンが、無視できる文字であるため、結果は、場合と同じにソフト ハイフンが含まれていない必要があるかvalueします。If the example is run on the .NET Framework 4.NET Framework 4 or later, in each case, because the soft hyphen is an ignorable character, the result is the same as if the soft hyphen had not been included in value. ソフト ハイフンのみを検索する場合、メソッドは、6、5 を返します。When searching for a soft hyphen only, the method returns 6 and 5. これらの値は、2 つの文字列の最後の文字のインデックスに対応します。These values correspond to the index of the last character in the two strings.

using System;

public class Example
{
   public static void Main()
   {
      string s1 = "ani\u00ADmal";
      string s2 = "animal";
      
      // Find the index of the last soft hyphen.
      Console.WriteLine(s1.LastIndexOf("\u00AD"));
      Console.WriteLine(s2.LastIndexOf("\u00AD"));
      
      // 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:
//       6
//       5
//       1
//       1
//       4
//       3
Module Example
   Public Sub Main()
      Dim softHyphen As String = ChrW(&h00AD)
      Dim s1 As String = "ani" + softHyphen + "mal"
      Dim s2 As String = "animal"
      
      ' Find the index of the last soft hyphen.
      Console.WriteLine(s1.LastIndexOf(softHyphen))
      Console.WriteLine(s2.LastIndexOf(softHyphen))
      
      ' 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"))
   End Sub
End Module
' The example displays the following output:
'       6
'       5
'       1
'       1
'       4
'       3

注意 (呼び出し元)

説明したよう文字列を使用するためのベスト プラクティス既定値を代入しを明示的に指定するパラメーターを必要とするメソッドを呼び出す代わりに文字列比較メソッドを呼び出さないようにすることをお勧めします。As explained in Best Practices for Using Strings, we recommend that you avoid calling string comparison methods that substitute default values and instead call methods that require parameters to be explicitly specified. 文字列インスタンス内の部分文字列の最後のインデックスを検索するには、現在のカルチャの比較規則を使用して、呼び出して、LastIndexOf(String, StringComparison)メソッドのオーバー ロードの値を持つCurrentCulturecomparisonTypeパラメーター。To find the last index of a substring within a string instance by using the comparison rules of the current culture, call the LastIndexOf(String, StringComparison) method overload with a value of CurrentCulture for its comparisonType parameter.

こちらもご覧ください

LastIndexOf(String, Int32, Int32, StringComparison) LastIndexOf(String, Int32, Int32, StringComparison) LastIndexOf(String, Int32, Int32, StringComparison) LastIndexOf(String, Int32, Int32, StringComparison)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of a specified string within this instance. 検索は指定された文字位置から開始し、文字列の開始に向かって後方に移動し、文字位置の指定された数だけ行われます。The search starts at a specified character position and proceeds backward toward the beginning of the string for the specified number of character positions. 指定した文字列を検索するときに実行する比較の種類をパラメーターで指定します。A parameter specifies the type of comparison to perform when searching for the specified string.

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

シークする文字列。The string to seek.

startIndex
Int32 Int32 Int32 Int32

検索が開始される位置。The search starting position. 検索は、このインスタンスの先頭に向かって startIndex から開始されます。The search proceeds from startIndex toward the beginning of this instance.

count
Int32 Int32 Int32 Int32

検査する文字位置の数。The number of character positions to examine.

comparisonType
StringComparison StringComparison StringComparison StringComparison

検索の規則を指定する列挙値の 1 つ。One of the enumeration values that specifies the rules for the search.

戻り値

その文字列が見つかった場合は、value パラメーターの 0 から始まる開始インデックス位置。見つからなかった場合、または現在のインスタンスが Empty と等しい場合は -1。The zero-based starting index position of the value parameter if that string is found, or -1 if it is not found or if the current instance equals Empty. valueEmpty の場合、戻り値は startIndex かこのインスタンスの最後のインデックス位置のいずれか小さい方です。If value is Empty, the return value is the smaller of startIndex and the last index position in this instance.

例外

count が負の値です。count is negative.

または-or- 現在のインスタンスが Empty と等しくなく、startIndex が負の値です。The current instance does not equal Empty, and startIndex is negative.

または-or- 現在のインスタンスが Empty と等しくなく、startIndex がこのインスタンスの長さより大きいです。The current instance does not equal Empty, and startIndex is greater than the length of this instance.

または-or- 現在のインスタンスが Empty と等しくなく、startIndex + 1 - count した値がこのインスタンス内にはない位置を指定しています。The current instance does not equal Empty, and startIndex + 1 - count specifies a position that is not within this instance.

または-or- 現在のインスタンスが Empty と等しく、start が -1 より小さいか 0 より大きいです。The current instance equals Empty and start is less than -1 or greater than zero.

または-or- 現在のインスタンスが Empty と等しく、count が 1 より大きいです。The current instance equals Empty and count is greater than 1.

comparisonType は有効な StringComparison 値ではありません。comparisonType is not a valid StringComparison value.

次の例では、3 つのオーバー ロード、LastIndexOfのさまざまな値を使用して別の文字列内の文字列の最後の出現箇所を検索するメソッド、StringComparison列挙体。The following example demonstrates three overloads of the LastIndexOf method that find the last occurrence of a string within another string using different values of the StringComparison enumeration.

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

Imports System
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 'Main
End Class 'Sample

'
'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 から開始します。Index numbering starts from zero. つまり、インデックス 0 の文字列の最初の文字は、最後が、 Length - 1。That is, the first character in the string is at index zero and the last is at Length - 1.

検索を開始、startIndex文字の位置および処理されるまで、旧バージョンとの進行状況valueが見つかるまたはcount文字位置します。The search begins at the startIndex character position and proceeds backward until either value is found or count character positions have been examined. たとえば場合、startIndexLength- 1、メソッドは逆方向に検索count文字、文字列の最後の文字から。For example, if startIndex is Length - 1, the method searches backward count characters from the last character in the string.

comparisonTypeを検索するパラメーターを指定します、value現在またはインバリアント カルチャを使用して、または区別しない検索を使用して、word または序数比較規則を使用してパラメーター。The comparisonType parameter specifies to search for the value parameter using the current or invariant culture, using a case-sensitive or case-insensitive search, and using word or ordinal comparison rules.

注意 (呼び出し元)

文字セットには無視できる文字が含まれています。これらの文字は、言語またはカルチャに依存した比較を実行する際には考慮されません。Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. カルチャに依存する検索の場合 (つまり、comparisonTypeOrdinal または OrdinalIgnoreCase でない場合)、value に無視できる文字が含まれていると、その文字を削除して検索した場合と同じ結果になります。In a culture-sensitive search (that is, if comparisonType is not Ordinal or OrdinalIgnoreCase), if value contains an ignorable character, the result is equivalent to searching with that character removed. 場合value1 つまたは複数の無視できる文字のみで構成されて、LastIndexOf(String, Int32, Int32, StringComparison)メソッドは常に返しますstartIndex、これは、検索の開始文字位置。If value consists only of one or more ignorable characters, the LastIndexOf(String, Int32, Int32, StringComparison) method always returns startIndex, which is the character position at which the search begins.

次の例では、LastIndexOf(String, Int32, Int32, StringComparison)メソッドを使用して、2 つの文字列で、その後にすべての"m"ソフト ハイフン (U + 00AD) の位置が最後の"m"の前に、最初の文字位置を検索します。In the following example, the LastIndexOf(String, Int32, Int32, StringComparison) method is used to find the position of a soft hyphen (U+00AD) followed by an "m" in all but the first character position before the final "m" in two strings. 文字列の 1 つのみに必要な部分文字列が含まれます。Only one of the strings contains the required substring. 例実行している場合、.NET Framework 4.NET Framework 4または後で、どちらの場合も、ソフト ハイフンが、無視できる文字であるため、メソッドのインデックスを返します、文字列内の"m"、カルチャに依存した比較を実行するとき。If the example is run on the .NET Framework 4.NET Framework 4 or later, in both cases, because the soft hyphen is an ignorable character, the method returns the index of "m" in the string when it performs a culture-sensitive comparison. 序数に基づく比較を実行するときに、部分文字列のみで見つけた最初の文字列。When it performs an ordinal comparison, however, it finds the substring only in the first string. 最初の文字列は、"m"の後にソフト ハイフンが含まれている場合、メソッドはソフト ハイフンのインデックスを返すが失敗したが代わりに、カルチャに依存した比較を実行するときに、"m"のインデックスを返しますに注意してください。Note that in the case of the first string, which includes the soft hyphen followed by an "m", the method fails to return the index of the soft hyphen but instead returns the index of the "m" when it performs a culture-sensitive comparison. このメソッドは、序数に基づく比較を実行したときのみ、最初の文字列に含まれるソフト ハイフンのインデックスを返します。The method returns the index of the soft hyphen in the first string only when it performs an ordinal comparison.

[!code-csharpSystem.String.LastIndexOf#24] [!code-vbSystem.String.LastIndexOf#24][!code-csharpSystem.String.LastIndexOf#24] [!code-vbSystem.String.LastIndexOf#24]

LastIndexOf(String, Int32) LastIndexOf(String, Int32) LastIndexOf(String, Int32) LastIndexOf(String, Int32)

指定された文字列がこのインスタンス内で最後に見つかった 0 から始まるインデックス位置をレポートします。Reports the zero-based index position of the last occurrence of a specified string within this instance. 検索は、指定された文字位置から開始され、文字列の先頭に向かって逆方向に進みます。The search starts at a specified character position and proceeds backward toward the beginning of the string.

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

シークする文字列。The string to seek.

startIndex
Int32 Int32 Int32 Int32

検索が開始される位置。The search starting position. 検索は、このインスタンスの先頭に向かって startIndex から開始されます。The search proceeds from startIndex toward the beginning of this instance.

戻り値

その文字列が見つかった場合は、value の 0 から始まる開始インデックス位置。見つからなかった場合、または現在のインスタンスが Empty と等しい場合は -1。The zero-based starting index position of value if that string is found, or -1 if it is not found or if the current instance equals Empty. valueEmpty の場合、戻り値は startIndex かこのインスタンスの最後のインデックス位置のいずれか小さい方です。If value is Empty, the return value is the smaller of startIndex and the last index position in this instance.

例外

現在のインスタンスが Empty と等しくなく、startIndex が 0 未満であるか、または現在のインスタンスの長さを超えています。The current instance does not equal Empty, and startIndex is less than zero or greater than the length of the current instance.

または-or- 現在のインスタンスが Empty と等しく、startIndex が -1 未満であるか、または 0 を超えています。The current instance equals Empty, and startIndex is less than -1 or greater than zero.

次の例では、ターゲット文字列の先頭に、ターゲット文字列の末尾からの操作のターゲット文字列の文字列のすべての出現箇所のインデックスを検索します。The following example finds the index of all occurrences of a string in target string, working from the end of the target string to the start of the target string.

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

      '#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 'Main 
End Class 'Sample
'
'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 から開始します。Index numbering starts from zero. つまり、インデックス 0 の文字列の最初の文字は、最後が、 Length - 1。That is, the first character in the string is at index zero and the last is at Length - 1.

検索を開始、startIndex文字位置のこのインスタンスと処理が進行するまで先頭に向かって後方valueが見つかるまたは最初の文字位置が検査されています。The search begins at the startIndex character position of this instance and proceeds backward toward the beginning until either value is found or the first character position has been examined. たとえば場合、startIndexLength- 1、メソッドは、先頭に文字列の最後の文字からのすべての文字を検索します。For example, if startIndex is Length - 1, the method searches every character from the last character in the string to the beginning.

このメソッドは、現在のカルチャを使用して単語 (大文字小文字を区別し、カルチャに依存する) 検索を実行します。This method performs a word (case-sensitive and culture-sensitive) search using the current culture.

文字セットには無視できる文字が含まれています。これらの文字は、言語またはカルチャに依存した比較を実行する際には考慮されません。Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. カルチャに依存した検索では、value に無視できる文字が含まれている場合、その文字を削除して検索した場合と同じ結果になります。In a culture-sensitive search, if value contains an ignorable character, the result is equivalent to searching with that character removed. 場合value1 つまたは複数の無視できる文字のみで構成されて、LastIndexOf(String, Int32)メソッドは常に返しますstartIndex、これは、検索の開始文字位置。If value consists only of one or more ignorable characters, the LastIndexOf(String, Int32) method always returns startIndex, which is the character position at which the search begins. 次の例では、LastIndexOf(String, Int32)ソフト ハイフン (U + 00AD) が含まれ、前または最後の"m"を文字列に含まれます部分文字列を検索するメソッドを使用します。In the following example, the LastIndexOf(String, Int32) method is used to find a substring that includes a soft hyphen (U+00AD) and that precedes or includes the final "m" in a string. 例実行している場合、.NET Framework 4.NET Framework 4または後で、検索文字列にソフト ハイフンが無視されるため、substrin を探すための呼び出しはソフト ハイフンと"m"で構成される部分文字列では、"m"の位置を返します、文字列内を検索するメソッドの呼び出しソフト ハイフンと"n"で構成される g では、"n"の位置を返します。If the example is run on the .NET Framework 4.NET Framework 4 or later, because the soft hyphen in the search string is ignored, calling the method to find a substring that consists of the soft hyphen and "m" returns the position of the "m" in the string, whereas calling it to find a substring that consists of the soft hyphen and "n" returns the position of the "n". メソッドが、"m"の値を表すのインデックスを返します、検索文字列には、ソフト ハイフンのみが含まれている、startIndexします。When the search string contains only the soft hyphen, the method returns the index of the "m", which represents the value of startIndex.

using System;

public class Example
{
   public static void Main()
   {
      int position = 0;
      string s1 = "ani\u00ADmal";
      string s2 = "animal";
      
      // Find the index of the soft hyphen.
      position = s1.LastIndexOf("m");
      Console.WriteLine("'m' at position {0}", position);
      if (position >= 0)
         Console.WriteLine(s1.LastIndexOf("\u00AD", position));

      position = s2.LastIndexOf("m");
      Console.WriteLine("'m' at position {0}", position);
      if (position >= 0)   
         Console.WriteLine(s2.LastIndexOf("\u00AD", position));
      
      // Find the index of the soft hyphen followed by "n".
      position = s1.LastIndexOf("m");
      Console.WriteLine("'m' at position {0}", position);
      if (position >= 0)
         Console.WriteLine(s1.LastIndexOf("\u00ADn", position));

      position = s2.LastIndexOf("m");
      Console.WriteLine("'m' at position {0}", 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 {0}", position);
      if (position >= 0)
         Console.WriteLine(s1.LastIndexOf("\u00ADm", position));

      position = s2.LastIndexOf("m");
      Console.WriteLine("'m' at position {0}", position);
      if (position >= 0)   
         Console.WriteLine(s2.LastIndexOf("\u00ADm", position));
   }
}
// The example displays the following output:
//       'm' at position 4
//       4
//       'm' at position 3
//       3
//       'm' at position 4
//       1
//       'm' at position 3
//       1
//       'm' at position 4
//       4
//       'm' at position 3
//       3
Module Example
   Public Sub Main()
      Dim position As Integer
      Dim softHyphen As String = ChrW(&h00AD)
      Dim s1 As String = "ani" + softHyphen + "mal"
      Dim s2 As String = "animal"
      
      ' Find the index of the soft hyphen.
      position = s1.LastIndexOf("m")
      Console.WriteLine("'m' at position {0}", position)
      If position >= 0 Then
         Console.WriteLine(s1.LastIndexOf(softHyphen, position))
      End If
         
      position = s2.LastIndexOf("m")
      Console.WriteLine("'m' at position {0}", position)
      If position >= 0 Then
         Console.WriteLine(s2.LastIndexOf(softHyphen, position))
      End If
      
      ' Find the index of the soft hyphen followed by "n".
      position = s1.LastIndexOf("m")
      Console.WriteLine("'m' at position {0}", position)
      If position >= 0 Then
         Console.WriteLine(s1.LastIndexOf(softHyphen + "n", position))
      End If
         
      position = s2.LastIndexOf("m")
      Console.WriteLine("'m' at position {0}", 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 {0}", position)
      If position >= 0 Then
         Console.WriteLine(s1.LastIndexOf(softHyphen + "m", position))
      End If
      
      position = s2.LastIndexOf("m")
      Console.WriteLine("'m' at position {0}", position)
      If position >= 0 Then
         Console.WriteLine(s2.LastIndexOf(softHyphen + "m", position))
      End If
   End Sub
End Module
' The example displays the following output:
'       'm' at position 4
'       4
'       'm' at position 3
'       3
'       'm' at position 4
'       1
'       'm' at position 3
'       1
'       'm' at position 4
'       4
'       'm' at position 3
'       3

注意 (呼び出し元)

説明したよう文字列を使用するためのベスト プラクティス既定値を代入しを明示的に指定するパラメーターを必要とするメソッドを呼び出す代わりに文字列比較メソッドを呼び出さないようにすることをお勧めします。As explained in Best Practices for Using Strings, we recommend that you avoid calling string comparison methods that substitute default values and instead call methods that require parameters to be explicitly specified. 現在のカルチャの比較規則を使用して特定の文字位置の前の部分文字列のインデックスを検索するには、呼び出し、LastIndexOf(String, Int32, StringComparison)メソッドのオーバー ロードの値を持つCurrentCulturecomparisonTypeパラメーター。To find the index of a substring that precedes a particular character position by using the comparison rules of the current culture, call the LastIndexOf(String, Int32, StringComparison) method overload with a value of CurrentCulture for its comparisonType parameter.

こちらもご覧ください

適用対象