String.LastIndexOfとは? わかりやすく解説

String.LastIndexOf メソッド (Char)

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

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

例外例外
例外の種類条件

ArgumentNullException

value が null 参照 (Visual Basic では Nothing) です。

解説解説
使用例使用例

次に示すのは、LastIndexOf メソッドを使用して String の文字を検索するコード例です。

// Create a Unicode String with 5 Greek Alpha characters
String szGreekAlpha = new String('\u0319',5);
// Create a Unicode String with a Greek Omega character
String szGreekOmega = new String(new char
 [] {'\u03A9','\u03A9','\u03A9'},2,1);

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

// Examine the result
Console.WriteLine(szGreekLetters);

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

Console.WriteLine("The Greek letter Alpha first appears at index " + ialpha
 +
    " and Omega last appears at index " + iomega + " in
 this String.");
// Create a Unicode String with 5 Greek Alpha characters
String^ szGreekAlpha = gcnew String( L'\x0319',5 );

// Create a Unicode String with a Greek Omega character
wchar_t charArray5[3] = {L'\x03A9',L'\x03A9',L'\x03A9'};
String^ szGreekOmega = gcnew String( charArray5,2,1 );
String^ szGreekLetters = String::Concat( szGreekOmega, szGreekAlpha, szGreekOmega->Clone()
 );

// Examine the result
Console::WriteLine( szGreekLetters );

// The first index of Alpha
int ialpha = szGreekLetters->IndexOf( L'\x0319' );

// The last index of Omega
int iomega = szGreekLetters->LastIndexOf( L'\x03A9' );
Console::WriteLine( String::Concat(  "The Greek letter Alpha first appears at
 index ", Convert::ToString( ialpha ) ) );
Console::WriteLine( String::Concat(  " and Omega last appears at index ",
 Convert::ToString( iomega ),  " in this
 String." ) );
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

String.LastIndexOf メソッド

このインスタンス内で最後に出現する指定 Unicode 文字または String のインデックス位置をレポートします。
オーバーロードの一覧オーバーロードの一覧

名前 説明
String.LastIndexOf (Char) このインスタンス内で最後に出現する指定 Unicode 文字のインデックス位置をレポートします。

.NET Compact Framework によってサポートされています。

String.LastIndexOf (String) 指定した String がこのインスタンス内で最後に見つかったインデックス位置をレポートします。

.NET Compact Framework によってサポートされています。

String.LastIndexOf (Char, Int32) このインスタンス内で最後に出現する指定 Unicode 文字のインデックス位置をレポートします。検索は、指定した文字位置から開始されます。

.NET Compact Framework によってサポートされています。

String.LastIndexOf (String, Int32) 指定した String がこのインスタンス内で最後に見つかったインデックス位置をレポートします。検索は、指定した文字位置から開始されます。

.NET Compact Framework によってサポートされています。

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

.NET Compact Framework によってサポートされています。

String.LastIndexOf (Char, Int32, Int32) このインスタンス内の部分文字列で最後に出現する指定 Unicode 文字のインデックス位置をレポートします。検索は指定した文字位置から開始され、指定した数の文字位置が検査されます。

.NET Compact Framework によってサポートされています。

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

.NET Compact Framework によってサポートされています。

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

.NET Compact Framework によってサポートされています。

String.LastIndexOf (String, Int32, Int32, StringComparison) 指定した String オブジェクトがこのインスタンス内で最後に見つかったインデックス位置をレポートします。パラメータは、現在の文字列での検索位置、現在の文字列で検索する文字の数、および指定した文字列に使用する検索の種類を指定します。

.NET Compact Framework によってサポートされています。

参照参照

関連項目

String クラス
String メンバ
System 名前空間
Char 構造体
IndexOf
IndexOfAny
LastIndexOfAny

String.LastIndexOf メソッド (Char, Int32)

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

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Function LastIndexOf ( _
    value As Char, _
    startIndex As Integer _
) As Integer
Dim instance As String
Dim value As Char
Dim startIndex As Integer
Dim returnValue As Integer

returnValue = instance.LastIndexOf(value, startIndex)
public int LastIndexOf (
    char value,
    int startIndex
)
public:
int LastIndexOf (
    wchar_t value, 
    int startIndex
)
public int LastIndexOf (
    char value, 
    int startIndex
)
public function LastIndexOf (
    value : char, 
    startIndex : int
) : int

パラメータ

value

シークする Unicode 文字。

startIndex

このインスタンス内の部分文字列の開始位置。

戻り値
その文字が見つかった場合は、value のインデックス位置。見つからなかった場合は -1。

例外例外
例外の種類条件

ArgumentNullException

value が null 参照 (Visual Basic では Nothing) です。

ArgumentOutOfRangeException

startIndex が、0 未満か、このインスタンスの長さを超えています。

解説解説

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

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

このメソッドは、序数 (カルチャに依存しない) 検索を実行します。この検索方法では、2 つの文字は Unicode スカラ値が等しいときだけ等価と見なされます。カルチャに依存した検索を実行するには、CompareInfo.LastIndexOf メソッドを使用します。このメソッドを使用して検索すると、合字の "A" (U+00C6) のような構成済み文字を表す Unicode 値は、'AE' (U+0041, U+0045) のようにその文字の構成要素が正しい順序で出現した場合、これらの構成要素と (カルチャの種類に応じて) 等価と見なされます。

使用例使用例

文字列の最後から先頭に向かって特定の文字を検索し、そのすべてのインデックス位置を取得するコード例を次に示します。

' 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
'
// 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)
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)
import System.*;

class Sample
{
    public static void main(String[]
 args)
    {
        String br1 = "0----+----1----+----2----+----3----+----4----+----5----+"
            + "----6----+-";
        String br2 = "01234567890123456789012345678901234567890123456789012345"
            + "67890123456";
        String str = "Now is the time for all good men to
 come to the aid of "
            + "their party.";
        int start;
        int at;

        start = str.get_Length() - 1;
        Console.WriteLine("All occurrences of 't' from position {0} to 0.",
 
            (Int32)start);
        Console.Write("{1}{0}", Environment.get_NewLine(), br1);
        Console.Write("{1}{0}", Environment.get_NewLine(), br2);
        Console.WriteLine("{1}{0}", Environment.get_NewLine(), 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} ", (Int32)at);
                start = at - 1;
            }
        }
        Console.Write("{0}{0}{0}", Environment.get_NewLine());
    } //main
} //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
*/
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

String.LastIndexOf メソッド (String)

指定した String がこのインスタンス内で最後に見つかったインデックス位置をレポートします。

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

例外例外
例外の種類条件

ArgumentNullException

value が null 参照 (Visual Basic では Nothing) です。

解説解説
使用例使用例

入力文字列の解析中の判定に LastIndexOf メソッドを使用する方法については、次のコード例を参照してください。

Imports System

Public Class EndsWithTest

    Public Shared 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 simply ends with a greater than
 symbol, it should not be modified>"}

        ' process an input file that contains html tags.
        ' this sample checks for multiple tags at the end of the line,
 rather than simply
        ' removing the last one.
        ' note: HTML markup tags always end in a greater than symbol
 (>).


        Console.WriteLine("The following lists the items before
 the ends have been stripped:")
        Console.WriteLine("-----------------------------------------------------------------")

        ' print out the initial array of strings
        Dim s As String
        For Each s In  strSource
            Console.WriteLine(s)

        Next s
        Console.WriteLine()

        Console.WriteLine("The following lists the items after
 the ends have been stripped:")
        Console.WriteLine("----------------------------------------------------------------")

        ' print out the array of strings
        For Each s In  strSource
            Console.WriteLine(StripEndTags(s))
        Next s

    End Sub 'Main

    Private Shared Function
 StripEndTags(item As String) As
 String

        ' try to find a tag at the end of the line using EndsWith
        If item.Trim().EndsWith(">")
 Then

            ' now search for the opening tag...
            Dim lastLocation As Integer
 = item.LastIndexOf("</")
            If lastLocation >= 0 Then

                ' remove the identified section, if it is a valid region
                item = item.Substring(0, lastLocation)
            End If
        End If

    Return Item
    End Function 'StripEndTags

End Class 'EndsWithTest
using System;

public class EndsWithTest {
    public static void Main()
 {

        // process an input file that contains html tags.
        // this sample checks for multiple tags at the end of the line,
 rather than simply
        // removing the last one.
        // note: HTML markup tags always end in a greater than symbol
 (>).

        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 simply ends with a greater than symbol, it should
 not be modified>" };

        Console.WriteLine("The following lists the items before the ends have
 been stripped:");
        Console.WriteLine("-----------------------------------------------------------------");

        // print out the initial array of strings
        foreach ( string s in
 strSource )
            Console.WriteLine( s );

        Console.WriteLine();

        Console.WriteLine("The following lists the items after the ends have
 been stripped:");
        Console.WriteLine("----------------------------------------------------------------");

        // print out the array of strings
        foreach ( string s in
 strSource )
            Console.WriteLine( StripEndTags( s ) );
    }

    private static string
 StripEndTags( string item ) {

            // try to find a tag at the end of the line using EndsWith
            if (item.Trim().EndsWith(">")) {

                // now search for the opening tag...
                int lastLocation = item.LastIndexOf( "</"
 );

                // remove the identified section, if it is a valid region
                if ( lastLocation >= 0 )
                    item =  item.Substring( 0, lastLocation );
            }

    return item;
    }
}
using namespace System;
using namespace System::Collections;
String^ StripEndTags( String^ item )
{
   
   // try to find a tag at the end of the line using EndsWith
   if ( item->Trim()->EndsWith( ">" ) )
   {
      
      // now search for the opening tag...
      int lastLocation = item->LastIndexOf( "</"
 );
      
      // remove the identified section, if it is a valid region
      if ( lastLocation >= 0 )
            item = item->Substring( 0, lastLocation );
   }

   return item;
}

int main()
{
   
   // process an input file that contains html tags.
   // this sample checks for multiple tags at the end of the line, rather
 than simply
   // removing the last one.
   // note: HTML markup tags always end in a greater than symbol (>).
   array<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 simply ends with a greater than symbol,
 it should not be modified>"};
   Console::WriteLine( "The following lists the items before the ends have been
 stripped:" );
   Console::WriteLine( "-----------------------------------------------------------------"
 );
   
   // print out the initial array of strings
   IEnumerator^ myEnum1 = strSource->GetEnumerator();
   while ( myEnum1->MoveNext() )
   {
      String^ s = safe_cast<String^>(myEnum1->Current);
      Console::WriteLine( s );
   }

   Console::WriteLine();
   Console::WriteLine( "The following lists the items after the ends have been
 stripped:" );
   Console::WriteLine( "----------------------------------------------------------------"
 );
   
   // print out the array of strings
   IEnumerator^ myEnum2 = strSource->GetEnumerator();
   while ( myEnum2->MoveNext() )
   {
      String^ s = safe_cast<String^>(myEnum2->Current);
      Console::WriteLine( StripEndTags( s ) );
   }
}

import System.*;

public class EndsWithTest
{
    public static void main(String[]
 args)
    {
        // process an input file that contains html tags.
        // this sample checks for multiple tags at the end of the line,
 
        // rather than simply removing the last one.
        // note: HTML markup tags always end in a greater than symbol
 (>).
        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 simply ends with a greater than symbol, it should not
 "
            + "be modified>" };

        Console.WriteLine("The following lists the items before the ends have
 "
            + "been stripped:");
        Console.WriteLine("---------------------------------------------------"
            + "--------------");

        // print out the initial array of strings
        for (int iCtr = 0; iCtr < strSource.get_Length();
 iCtr++) {
            String s = (String)strSource.get_Item(iCtr);
            Console.WriteLine(s);
        }
        Console.WriteLine();
        Console.WriteLine("The following lists the items after the ends have
 "
            + "been stripped:");
        Console.WriteLine("---------------------------------------------------"
            + "-------------");

        // print out the array of strings
        for (int iCtr = 0; iCtr < strSource.get_Length();
 iCtr++) {
            String s = (String)strSource.get_Item(iCtr);
            Console.WriteLine(StripEndTags(s));
        }
    } //main

    private static String StripEndTags(String
 item)
    {
        // try to find a tag at the end of the line using EndsWith
        if (item.Trim().EndsWith(">")) {
            // now search for the opening tag...
            int lastLocation = item.LastIndexOf("</");
            // remove the identified section, if it is a valid region
            if (lastLocation >= 0) {
                item = item.Substring(0, lastLocation);
            }
        }
        return item;
    } //StripEndTags
} //EndsWithTest
import System;

public class EndsWithTest {
    public static function
 Main() : void {

        // process an input file that contains html tags.
        // this sample checks for multiple tags at the end of the line,
 rather than simply
        // removing the last one.
        // note: HTML markup tags always end in a greater than symbol
 (>).

        var strSource : 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 simply ends with a greater than symbol, it should
 not be modified>"];

        Console.WriteLine("The following lists the items before the ends have
 been stripped:");
        Console.WriteLine("-----------------------------------------------------------------");

        // print out the initial array of strings
        for( var i : int
 in strSource )
            Console.WriteLine( strSource[i] );

        Console.WriteLine();
        Console.WriteLine("The following lists the items after the ends have
 been stripped:");
        Console.WriteLine("----------------------------------------------------------------");
        // print out the array of strings
        for( i in strSource )
            Console.WriteLine( StripEndTags( strSource[i] ) );
    }

    private static function
 StripEndTags( item : String ) : String {
        // try to find a tag at the end of the line using EndsWith
        if (item.Trim().EndsWith(">")) {
            // now search for the opening tag...
            var lastLocation : int = item.LastIndexOf(
 "</" );
            // remove the identified section, if it is a valid region
            if ( lastLocation >= 0 )
                item =  item.Substring( 0, lastLocation );
        }
        return item;
    }
}
EndsWithTest.Main();
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

String.LastIndexOf メソッド (String, Int32)

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

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Function LastIndexOf ( _
    value As String, _
    startIndex As Integer _
) As Integer
Dim instance As String
Dim value As String
Dim startIndex As Integer
Dim returnValue As Integer

returnValue = instance.LastIndexOf(value, startIndex)
public int LastIndexOf (
    string value,
    int startIndex
)
public:
int LastIndexOf (
    String^ value, 
    int startIndex
)
public int LastIndexOf (
    String value, 
    int startIndex
)
public function LastIndexOf (
    value : String, 
    startIndex : int
) : int

パラメータ

value

シークする String。

startIndex

検索が開始される位置。

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

例外例外
例外の種類条件

ArgumentNullException

value が null 参照 (Visual Basic では Nothing) です。

ArgumentOutOfRangeException

startIndex が 0 未満か、インスタンス内にない位置を指定しています。

解説解説
使用例使用例

対象文字列の最後から先頭に向かって特定の文字列を検索し、そのすべてのインデックス位置を取得するコード例を次に示します。

' 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
'
'
// 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)
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)
import System.*;

class Sample
{
    public static void main(String[]
 args)
    {
        String br1 = "0----+----1----+----2----+----3----+----4----+----5----+"
            + "----6----+-";
        String br2 = "01234567890123456789012345678901234567890123456789012345"
            + "67890123456";
        String str = "Now is the time for all good men to
 come to the aid of "
            + "their party.";
        int start;
        int at;

        start = str.get_Length() - 1;
        Console.WriteLine("All occurrences of 'he' from position {0} to 0."
,
            (Int32)start);
        Console.Write("{1}{0}", Environment.get_NewLine(), br1);
        Console.Write("{1}{0}", Environment.get_NewLine(), br2);
        Console.WriteLine("{1}{0}", Environment.get_NewLine(), 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} ", (Int32)at);
                start = at - 1;
            }
        }
        Console.Write("{0}{0}{0}", Environment.get_NewLine());
    } //main
} //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


*/
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

String.LastIndexOf メソッド (String, Int32, Int32)

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

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Function LastIndexOf ( _
    value As String, _
    startIndex As Integer, _
    count As Integer _
) As Integer
Dim instance As String
Dim value As String
Dim startIndex As Integer
Dim count As Integer
Dim returnValue As Integer

returnValue = instance.LastIndexOf(value, startIndex, count)
public int LastIndexOf (
    string value,
    int startIndex,
    int count
)
public:
int LastIndexOf (
    String^ value, 
    int startIndex, 
    int count
)
public int LastIndexOf (
    String value, 
    int startIndex, 
    int count
)
public function LastIndexOf (
    value : String, 
    startIndex : int, 
    count : int
) : int

パラメータ

value

シークする String。

startIndex

検索が開始される位置。

count

検査する文字位置の数。

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

例外例外
例外の種類条件

ArgumentNullException

value が null 参照 (Visual Basic では Nothing) です。

ArgumentOutOfRangeException

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

または

startIndex に count を足した数が、このインスタンス内にない位置を示しています。

解説解説
使用例使用例

部分文字列の最後から先頭に向かって特定の文字列を検索し、そのすべてのインデックス位置を取得するコード例を次に示します。

' 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
'
'
// 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)
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)
import System.*;

class Sample
{
    public static void main(String[]
 args)
    {
        String br1 = "0----+----1----+----2----+----3----+----4----+----5----+"
            + "----6----+-";
        String br2 = "01234567890123456789012345678901234567890123456789012345"
            + "67890123456";
        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.get_Length() - 1;
        end = start / 2 - 1;
        Console.WriteLine("All occurrences of 'he' from position {0} to {1}."
,
            (Int32)start, (Int32)end);
        Console.Write("{1}{0}", Environment.get_NewLine(), br1);
        Console.Write("{1}{0}", Environment.get_NewLine(), br2);
        Console.WriteLine("{1}{0}", Environment.get_NewLine(), 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} ", (Int32)at);
                start = at - 1;
            }
        }
        Console.Write("{0}{0}{0}", Environment.get_NewLine());
    } //main
} //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
*/
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

String.LastIndexOf メソッド (Char, Int32, Int32)

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

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Function LastIndexOf ( _
    value As Char, _
    startIndex As Integer, _
    count As Integer _
) As Integer
Dim instance As String
Dim value As Char
Dim startIndex As Integer
Dim count As Integer
Dim returnValue As Integer

returnValue = instance.LastIndexOf(value, startIndex, count)
public int LastIndexOf (
    char value,
    int startIndex,
    int count
)
public:
int LastIndexOf (
    wchar_t value, 
    int startIndex, 
    int count
)
public int LastIndexOf (
    char value, 
    int startIndex, 
    int count
)
public function LastIndexOf (
    value : char, 
    startIndex : int, 
    count : int
) : int

パラメータ

value

シークする Unicode 文字。

startIndex

このインスタンス内の部分文字列の開始位置。

count

検査する文字位置の数。

戻り値
その文字が見つかった場合は、value のインデックス位置。見つからなかった場合は -1。

例外例外
例外の種類条件

ArgumentNullException

value が null 参照 (Visual Basic では Nothing) です。

ArgumentOutOfRangeException

startIndex または count が 0 未満か、またはこのインスタンスの長さより大きい値です。

解説解説

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

このメソッドは、インスタンスの startIndex の文字位置から検索を開始し、value が見つかるか、または count の文字位置に到達するまで、インスタンスの先頭へ向かって逆方向に検索を実行します。検索では、大文字と小文字が区別されます。

このメソッドは、序数 (カルチャに依存しない) 検索を実行します。この検索方法では、2 つの文字は Unicode スカラ値が等しいときだけ等価と見なされます。カルチャに依存した検索を実行するには、CompareInfo.LastIndexOf メソッドを使用します。このメソッドを使用して検索すると、合字の "A" (U+00C6) のような構成済み文字を表す Unicode 値は、'AE' (U+0041, U+0045) のようにその文字の構成要素が正しい順序で出現した場合、これらの構成要素と (カルチャの種類に応じて) 等価と見なされます。

使用例使用例

部分文字列の最後から先頭に向かって特定の文字を検索し、そのすべてのインデックス位置を取得するコード例を次に示します。

' 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
'
'
// 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)
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)
import System.*;

class Sample
{
    public static void main(String[]
 args)
    {
        String br1 = "0----+----1----+----2----+----3----+----4----+----5----+"
            + "----6----+-";
        String br2 = "01234567890123456789012345678901234567890123456789012345"
            + "67890123456";
        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.get_Length() - 1;
        end = start / 2 - 1;
        Console.WriteLine("All occurrences of 't' from position {0} to {1}."
,
            (Int32)start, (Int32)end);
        Console.Write("{1}{0}", Environment.get_NewLine(), br1);
        Console.Write("{1}{0}", Environment.get_NewLine(), br2);
        Console.WriteLine("{1}{0}", Environment.get_NewLine(), 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} ", (Int32)at);
                start = at - 1;
            }
        }
        Console.Write("{0}{0}{0}", Environment.get_NewLine());
    } //main
} //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


*/
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

String.LastIndexOf メソッド (String, Int32, StringComparison)

メモ : このメソッドは、.NET Framework version 2.0 で新しく追加されたものです。

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

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Function LastIndexOf ( _
    value As String, _
    startIndex As Integer, _
    comparisonType As StringComparison _
) As Integer
Dim instance As String
Dim value As String
Dim startIndex As Integer
Dim comparisonType As StringComparison
Dim returnValue As Integer

returnValue = instance.LastIndexOf(value, startIndex, comparisonType)
public int LastIndexOf (
    string value,
    int startIndex,
    StringComparison comparisonType
)
public:
int LastIndexOf (
    String^ value, 
    int startIndex, 
    StringComparison comparisonType
)
public int LastIndexOf (
    String value, 
    int startIndex, 
    StringComparison comparisonType
)
public function LastIndexOf (
    value : String, 
    startIndex : int, 
    comparisonType : StringComparison
) : int

パラメータ

value

シークする String オブジェクト。

startIndex

検索が開始される位置。

comparisonType

System.StringComparison 値の 1 つ。

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

例外例外
例外の種類条件

ArgumentNullException

value が null 参照 (Visual Basic では Nothing) です。

ArgumentOutOfRangeException

startIndex が 0 未満か、インスタンス内にない位置を指定しています。

ArgumentException

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

解説解説

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

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

検索は startIndex 文字の位置で開始され、value が見つかるか、またはインデックス位置の 0 に到達するまで逆方向に実行されます。

使用例使用例

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

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

*/
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

String.LastIndexOf メソッド (String, Int32, Int32, StringComparison)

メモ : このメソッドは、.NET Framework version 2.0 で新しく追加されたものです。

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

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Function LastIndexOf ( _
    value As String, _
    startIndex As Integer, _
    count As Integer, _
    comparisonType As StringComparison _
) As Integer
Dim instance As String
Dim value As String
Dim startIndex As Integer
Dim count As Integer
Dim comparisonType As StringComparison
Dim returnValue As Integer

returnValue = instance.LastIndexOf(value, startIndex, count, comparisonType)
public int LastIndexOf (
    string value,
    int startIndex,
    int count,
    StringComparison comparisonType
)
public:
int LastIndexOf (
    String^ value, 
    int startIndex, 
    int count, 
    StringComparison comparisonType
)
public int LastIndexOf (
    String value, 
    int startIndex, 
    int count, 
    StringComparison comparisonType
)
public function LastIndexOf (
    value : String, 
    startIndex : int, 
    count : int, 
    comparisonType : StringComparison
) : int

パラメータ

value

シークする String オブジェクト。

startIndex

検索が開始される位置。

count

検査する文字位置の数。

comparisonType

System.StringComparison 値の 1 つ。

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

例外例外
例外の種類条件

ArgumentNullException

value が null 参照 (Visual Basic では Nothing) です。

ArgumentOutOfRangeException

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

または

startIndex に count を足した数が、このインスタンス内にない位置を示しています。

ArgumentException

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

解説解説

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

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

この検索は、startIndex の文字位置から開始し、value が見つかるか、count の文字位置に到達するまで、逆方向に検索を実行します。

使用例使用例

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

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

*/
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

String.LastIndexOf メソッド (String, StringComparison)

メモ : このメソッドは、.NET Framework version 2.0 で新しく追加されたものです。

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

名前空間: System
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Function LastIndexOf ( _
    value As String, _
    comparisonType As StringComparison _
) As Integer
Dim instance As String
Dim value As String
Dim comparisonType As StringComparison
Dim returnValue As Integer

returnValue = instance.LastIndexOf(value, comparisonType)
public int LastIndexOf (
    string value,
    StringComparison comparisonType
)
public:
int LastIndexOf (
    String^ value, 
    StringComparison comparisonType
)
public int LastIndexOf (
    String value, 
    StringComparison comparisonType
)
public function LastIndexOf (
    value : String, 
    comparisonType : StringComparison
) : int

パラメータ

value

シークする String オブジェクト。

comparisonType

System.StringComparison 値の 1 つ。

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

例外例外
例外の種類条件

ArgumentNullException

value が null 参照 (Visual Basic では Nothing) です。

ArgumentException

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

解説解説

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

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

使用例使用例

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

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

*/
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照



英和和英テキスト翻訳

英語⇒日本語日本語⇒英語

辞書ショートカット

すべての辞書の索引

「String.LastIndexOf」の関連用語

String.LastIndexOfのお隣キーワード

   

英語⇒日本語
日本語⇒英語
   



String.LastIndexOfのページの著作権

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2026 Microsoft.All rights reserved.

©2026 GRAS Group, Inc.RSS