String.LastIndexOf メソッド
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
指定した Unicode 文字または文字列がこのインスタンス内で最後に出現した位置の 0 から始まるインデックス位置を報告します。 このメソッドは、このインスタンスで文字または文字列が見つからない場合に -1 を返します。
オーバーロード
LastIndexOf(String, Int32, Int32, StringComparison) |
このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は指定した文字位置から開始し、指定した文字数の文字列の先頭に向かって後方に進みます。 パラメーターは、指定した文字列を検索するときに実行する比較の種類を指定します。 |
LastIndexOf(String, Int32, Int32) |
このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は、指定した文字位置から開始し、指定された文字数の文字列の先頭に向かって後方に進みます。 |
LastIndexOf(Char, Int32, Int32) |
指定した Unicode 文字がこのインスタンス内の部分文字列内で最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は、指定した文字位置から開始し、指定された文字数の文字列の先頭に向かって後方に進みます。 |
LastIndexOf(String, StringComparison) |
現在の String オブジェクト内で指定した文字列が最後に出現した位置の 0 から始まるインデックスを報告します。 パラメーターは、指定した文字列に使用する検索の種類を指定します。 |
LastIndexOf(String, Int32, StringComparison) |
現在の String オブジェクト内で指定した文字列が最後に出現した位置の 0 から始まるインデックスを報告します。 検索は指定した文字位置から開始し、文字列の先頭に向かって後方に進みます。 パラメーターは、指定した文字列を検索するときに実行する比較の種類を指定します。 |
LastIndexOf(Char, Int32) |
指定した Unicode 文字がこのインスタンス内で最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は指定した文字位置から開始し、文字列の先頭に向かって後方に進みます。 |
LastIndexOf(String) |
このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。 |
LastIndexOf(Char) |
指定した Unicode 文字がこのインスタンス内で最後に出現した位置の、0 から始まるインデックス位置を報告します。 |
LastIndexOf(String, Int32) |
このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は指定した文字位置から開始し、文字列の先頭に向かって後方に進みます。 |
LastIndexOf(String, Int32, Int32, StringComparison)
このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は指定した文字位置から開始し、指定した文字数の文字列の先頭に向かって後方に進みます。 パラメーターは、指定した文字列を検索するときに実行する比較の種類を指定します。
public:
int LastIndexOf(System::String ^ value, int startIndex, int count, StringComparison comparisonType);
public int LastIndexOf (string value, int startIndex, int count, StringComparison comparisonType);
member this.LastIndexOf : string * int * int * StringComparison -> int
Public Function LastIndexOf (value As String, startIndex As Integer, count As Integer, comparisonType As StringComparison) As Integer
パラメーター
- value
- String
シークする文字列。
- startIndex
- Int32
検索開始位置。 検索は、startIndex
からこのインスタンスの先頭に進みます。
- count
- Int32
調べる文字位置の数。
- comparisonType
- StringComparison
検索の規則を指定する列挙値の 1 つ。
戻り値
その文字列が見つかった場合は、value
パラメーターの 0 から始まる開始インデックス位置。見つからない場合、または現在のインスタンスが Empty等しい場合は -1。
例外
value
は null
です。
count
は負の値です。
-又は-
現在のインスタンスは Empty等しくなく、startIndex
は負の値です。
-又は-
現在のインスタンスが Empty等しくなく、startIndex
がこのインスタンスの長さを超えています。
-又は-
現在のインスタンスは Emptyと等しくなく、startIndex
+ 1 - count
は、このインスタンス内にない位置を指定します。
-又は-
現在のインスタンスは Empty と等しく、startIndex
が -1 未満か、0 より大きい値です。
-又は-
現在のインスタンスは Empty、count
は 1 より大きい値です。
comparisonType
は有効な StringComparison 値ではありません。
例
次の例では、StringComparison 列挙型の異なる値を使用して、別の文字列内で文字列が最後に出現する箇所を検索する、LastIndexOf メソッドの 3 つのオーバーロードを示します。
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
using System;
using System.Threading;
using System.Globalization;
class Sample
{
public static void Main()
{
string intro = "Find the last occurrence of a character using different " +
"values of StringComparison.";
string resultFmt = "Comparison: {0,-28} Location: {1,3}";
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
string CapitalAWithRing = "\u00c5";
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
string cat = "A Cheshire c" + "\u0061\u030a" + "t";
int loc = 0;
StringComparison[] scValues = {
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
StringComparison.OrdinalIgnoreCase };
// Clear the screen and display an introduction.
Console.Clear();
Console.WriteLine(intro);
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("The current culture is \"{0}\" - {1}.",
Thread.CurrentThread.CurrentCulture.Name,
Thread.CurrentThread.CurrentCulture.DisplayName);
// Display the string to search for and the string to search.
Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"",
CapitalAWithRing, cat);
Console.WriteLine();
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
Console.WriteLine("Part 1: Start index and count are specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion. Specify the
// start index.
Console.WriteLine("\nPart 2: Start index is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, sc);
Console.WriteLine(resultFmt, sc, loc);
}
}
}
/*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*/
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
open System
open System.Threading
open System.Globalization
let intro = "Find the last occurrence of a character using different values of StringComparison."
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let CapitalAWithRing = "\u00c5"
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues =
[| StringComparison.CurrentCulture
StringComparison.CurrentCultureIgnoreCase
StringComparison.InvariantCulture
StringComparison.InvariantCultureIgnoreCase
StringComparison.Ordinal
StringComparison.OrdinalIgnoreCase |]
// Clear the screen and display an introduction.
Console.Clear()
printfn $"{intro}"
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."
// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
printfn "Part 1: Start index and count are specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*)
' This code example demonstrates the
' System.String.LastIndexOf(String, ..., StringComparison) methods.
Imports System.Threading
Imports System.Globalization
Class Sample
Public Shared Sub Main()
Dim intro As String = "Find the last occurrence of a character using different " & _
"values of StringComparison."
Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
' Define a string to search for.
' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
Dim CapitalAWithRing As String = "Å"
' Define a string to search.
' The result of combining the characters LATIN SMALL LETTER A and COMBINING
' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
Dim cat As String = "A Cheshire c" & "å" & "t"
Dim loc As Integer = 0
Dim scValues As StringComparison() = { _
StringComparison.CurrentCulture, _
StringComparison.CurrentCultureIgnoreCase, _
StringComparison.InvariantCulture, _
StringComparison.InvariantCultureIgnoreCase, _
StringComparison.Ordinal, _
StringComparison.OrdinalIgnoreCase }
Dim sc As StringComparison
' Clear the screen and display an introduction.
Console.Clear()
Console.WriteLine(intro)
' Display the current culture because culture affects the result. For example,
' try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
Console.WriteLine("The current culture is ""{0}"" - {1}.", _
Thread.CurrentThread.CurrentCulture.Name, _
Thread.CurrentThread.CurrentCulture.DisplayName)
' Display the string to search for and the string to search.
Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
CapitalAWithRing, cat)
Console.WriteLine()
' Note that in each of the following searches, we look for
' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
' the string was not found.
' Search using different values of StringComparsion. Specify the start
' index and count.
Console.WriteLine("Part 1: Start index and count are specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion. Specify the
' start index.
Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion.
Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
End Sub
End Class
'
'Note: This code example was executed on a console whose user interface
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the last occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
注釈
インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。
検索は startIndex
文字位置から始まり、value
が見つかるか、文字位置 count
調べるまで後方に進みます。 たとえば、startIndex
が Length - 1 の場合、メソッドは文字列の最後の文字から後方 count
文字を検索します。
comparisonType
パラメーターは、次を使用して value
パラメーターを検索するように指定します。
- 現在のカルチャまたはインバリアント カルチャ。
- 大文字と小文字を区別する検索または大文字と小文字を区別しない検索。
- 単語または序数の比較規則。
注意 (呼び出し元)
文字セットには無視できる文字が含まれます。これは、言語的またはカルチャに依存する比較を実行するときに考慮されない文字です。 カルチャに依存する検索 (つまり、comparisonType
が Ordinal または OrdinalIgnoreCaseでない場合) では、value
に無視できる文字が含まれている場合、結果はその文字を削除して検索するのと同じです。
次の例では、LastIndexOf(String, Int32, Int32, StringComparison) メソッドを使用して、ソフト ハイフン (U+00AD) の位置の後に、2 つの文字列の最後の "m" の前の最初の文字位置以外のすべてで "m" を検索します。 必要な部分文字列を含む文字列は 1 つだけです。 この例が .NET Framework 4 以降で実行されている場合、どちらの場合も、ソフト ハイフンは無視できる文字であるため、カルチャに依存する比較を実行すると、メソッドは文字列内の "m" のインデックスを返します。 ただし、序数比較を実行すると、最初の文字列内でのみ部分文字列が検索されます。 ソフト ハイフンの後に "m" が続く最初の文字列の場合、カルチャに依存する比較を実行すると、メソッドは "m" のインデックスを返します。 メソッドは、序数比較を実行する場合にのみ、最初の文字列のソフト ハイフンのインデックスを返します。
string searchString = "\u00ADm";
string s1 = "ani\u00ADmal";
string s2 = "animal";
int position;
position = s1.LastIndexOf('m');
if (position >= 1)
{
Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture));
Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.Ordinal));
}
position = s2.LastIndexOf('m');
if (position >= 1)
{
Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture));
Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.Ordinal));
}
// The example displays the following output:
//
// 4
// 3
// 3
// -1
let searchString = "\u00ADm"
let s1 = "ani\u00ADmal"
let s2 = "animal"
let position = s1.LastIndexOf 'm'
if position >= 1 then
printfn $"{s1.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture)}"
printfn $"{s1.LastIndexOf(searchString, position, position, StringComparison.Ordinal)}"
let position = s2.LastIndexOf 'm'
if position >= 1 then
printfn $"{s2.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture)}"
printfn $"{s2.LastIndexOf(searchString, position, position, StringComparison.Ordinal)}"
// The example displays the following output:
//
// 4
// 3
// 3
// -1
Dim searchString As String = ChrW(&HAD) + "m"
Dim s1 As String = "ani" + ChrW(&HAD) + "m"
Dim s2 As String = "animal"
Dim position As Integer
position = s1.LastIndexOf("m"c)
If position >= 1 Then
Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture))
Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.Ordinal))
End If
position = s2.LastIndexOf("m"c)
If position >= 1 Then
Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture))
Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.Ordinal))
End If
' The example displays the following output:
'
' 4
' 3
' 3
' -1
適用対象
LastIndexOf(String, Int32, Int32)
このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は、指定した文字位置から開始し、指定された文字数の文字列の先頭に向かって後方に進みます。
public:
int LastIndexOf(System::String ^ value, int startIndex, int count);
public int LastIndexOf (string value, int startIndex, int count);
member this.LastIndexOf : string * int * int -> int
Public Function LastIndexOf (value As String, startIndex As Integer, count As Integer) As Integer
パラメーター
- value
- String
シークする文字列。
- startIndex
- Int32
検索開始位置。 検索は、startIndex
からこのインスタンスの先頭に進みます。
- count
- Int32
調べる文字位置の数。
戻り値
その文字列が見つかった場合は、value
の 0 から始まる開始インデックス位置。見つからない場合、または現在のインスタンスが Empty等しい場合は -1。
例外
value
は null
です。
count
は負の値です。
-又は-
現在のインスタンスは Empty等しくなく、startIndex
は負の値です。
-又は-
現在のインスタンスが Empty等しくなく、startIndex
がこのインスタンスの長さを超えています。
-又は-
現在のインスタンスは Empty等しくなく、startIndex
- count
+ 1 は、このインスタンス内にない位置を指定します。
-又は-
現在のインスタンスは Empty と等しく、startIndex
が -1 未満か、0 より大きい値です。
-又は-
現在のインスタンスは Empty、count
は 1 より大きい値です。
例
次の例では、部分文字列の末尾から部分文字列の先頭まで、文字列のすべての出現箇所のインデックスを検索します。
// Sample for String::LastIndexOf(String, Int32, Int32)
using namespace System;
int main()
{
String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
String^ str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
int count;
int end;
start = str->Length - 1;
end = start / 2 - 1;
Console::WriteLine( "All occurrences of 'he' from position {0} to {1}.", start, end );
Console::WriteLine( "{1}{0}{2}{0}{3}{0}", Environment::NewLine, br1, br2, str );
Console::Write( "The string 'he' occurs at position(s): " );
count = 0;
at = 0;
while ( (start > -1) && (at > -1) )
{
count = start - end; //Count must be within the substring.
at = str->LastIndexOf( "he", start, count );
if ( at > -1 )
{
Console::Write( "{0} ", at );
start = at - 1;
}
}
Console::Write( "{0} {0} {0}", Environment::NewLine );
}
/*
This example produces the following results:
All occurrences of 'he' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45
*/
// Sample for String.LastIndexOf(String, Int32, Int32)
using System;
class Sample {
public static void Main() {
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
string str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
int count;
int end;
start = str.Length-1;
end = start/2 - 1;
Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, end);
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The string 'he' occurs at position(s): ");
count = 0;
at = 0;
while((start > -1) && (at > -1))
{
count = start - end; //Count must be within the substring.
at = str.LastIndexOf("he", start, count);
if (at > -1)
{
Console.Write("{0} ", at);
start = at - 1;
}
}
Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
This example produces the following results:
All occurrences of 'he' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45
*/
// Sample for String.LastIndexOf(String, Int32, Int32)
open System
let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."
let mutable start = str.Length-1
let last = start / 2 - 1
printfn $"All occurrences of 'he' from position {start} to {last}."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The string 'he' occurs at position(s): "
let mutable at = 0
while (start > -1) && (at > -1) do
let count = start - last //Count must be within the substring.
at <- str.LastIndexOf("he", start, count)
if at > -1 then
printf $"{at} "
start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 'he' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45
*)
' Sample for String.LastIndexOf(String, Int32, Int32)
_
Class Sample
Public Shared Sub Main()
Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
Dim str As String = "Now is the time for all good men to come to the aid of their party."
Dim start As Integer
Dim at As Integer
Dim count As Integer
Dim [end] As Integer
start = str.Length - 1
[end] = start / 2 - 1
Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, [end])
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
Console.Write("The string 'he' occurs at position(s): ")
count = 0
at = 0
While start > - 1 And at > - 1
count = start - [end] 'Count must be within the substring.
at = str.LastIndexOf("he", start, count)
If at > - 1 Then
Console.Write("{0} ", at)
start = at - 1
End If
End While
Console.Write("{0}{0}{0}", Environment.NewLine)
End Sub
End Class
'
'This example produces the following results:
'All occurrences of 'he' from position 66 to 32.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The string 'he' occurs at position(s): 56 45
'
'
注釈
インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。
検索は、このインスタンスの startIndex
文字位置から始まり、value
が見つかるか、文字位置が調べられるまで、先頭 count
戻ります。 たとえば、startIndex
が Length - 1 の場合、メソッドは文字列の最後の文字から後方 count
文字を検索します。
このメソッドは、現在のカルチャを使用して単語 (大文字と小文字が区別され、カルチャに依存する) 検索を実行します。
文字セットには無視できる文字が含まれます。これは、言語的またはカルチャに依存する比較を実行するときに考慮されない文字です。 カルチャに依存する検索では、value
に無視できる文字が含まれている場合、その文字を削除した場合の検索と同じ結果になります。
次の例では、LastIndexOf メソッドを使用して、ソフト ハイフン (U+00AD) の後に 2 つの文字列の "m" または "n" が続く位置を検索します。 ソフト ハイフンを含む文字列は 1 つだけです。 ソフト ハイフンの後に "m" が続く文字列の場合、LastIndexOf
は、ソフト ハイフンの後に "m" が続く場合、"m" のインデックスを返します。
int position = 0;
string s1 = "ani\u00ADmal";
string s2 = "animal";
// Find the index of the soft hyphen followed by "n".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s1.LastIndexOf("\u00ADn", position, position + 1));
position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s2.LastIndexOf("\u00ADn", position, position + 1));
// Find the index of the soft hyphen followed by "m".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s1.LastIndexOf("\u00ADm", position, position + 1));
position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s2.LastIndexOf("\u00ADm", position, position + 1));
// The example displays the following output:
//
// 'm' at position 4
// 1
// 'm' at position 3
// 1
// 'm' at position 4
// 4
// 'm' at position 3
// 3
let s1 = "ani\u00ADmal"
let s2 = "animal"
// Find the index of the soft hyphen followed by "n".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s1.LastIndexOf("\u00ADn", position, position + 1)}"""
let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s2.LastIndexOf("\u00ADn", position, position + 1)}"""
// Find the index of the soft hyphen followed by "m".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s1.LastIndexOf("\u00ADm", position, position + 1)}"""
let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s2.LastIndexOf("\u00ADm", position, position + 1)}"""
// The example displays the following output:
//
// 'm' at position 4
// 1
// 'm' at position 3
// 1
// 'm' at position 4
// 4
// 'm' at position 3
// 3
Dim position As Integer
Dim softHyphen As String = ChrW(&HAD)
Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"
' Find the index of the soft hyphen followed by "n".
position = s1.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s1.LastIndexOf(softHyphen + "n", position, position + 1))
End If
position = s2.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s2.LastIndexOf(softHyphen + "n", position, position + 1))
End If
' Find the index of the soft hyphen followed by "m".
position = s1.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s1.LastIndexOf(softHyphen + "m", position, position + 1))
End If
position = s2.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s2.LastIndexOf(softHyphen + "m", position, position + 1))
End If
' The example displays the following output:
'
' 'm' at position 4
' 1
' 'm' at position 3
' 1
' 'm' at position 4
' 4
' 'm' at position 3
' 3
注意 (呼び出し元)
文字列を使用するためのベスト プラクティス comparisonType
パラメーターの値を CurrentCulture して明示的に意図を通知します。 言語に対応した比較が必要ない場合は、Ordinalの使用を検討してください。
こちらもご覧ください
適用対象
LastIndexOf(Char, Int32, Int32)
指定した Unicode 文字がこのインスタンス内の部分文字列内で最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は、指定した文字位置から開始し、指定された文字数の文字列の先頭に向かって後方に進みます。
public:
int LastIndexOf(char value, int startIndex, int count);
public int LastIndexOf (char value, int startIndex, int count);
member this.LastIndexOf : char * int * int -> int
Public Function LastIndexOf (value As Char, startIndex As Integer, count As Integer) As Integer
パラメーター
- value
- Char
シークする Unicode 文字。
- startIndex
- Int32
検索の開始位置。 検索は、startIndex
からこのインスタンスの先頭に進みます。
- count
- Int32
調べる文字位置の数。
戻り値
その文字が見つかった場合は value
の 0 から始まるインデックス位置。見つからない場合、または現在のインスタンスが Empty等しい場合は -1。
例外
現在のインスタンスが Empty等しくなく、startIndex
が 0 未満であるか、このインスタンスの長さ以上です。
-又は-
現在のインスタンスは Empty等しくなく、startIndex
- count
+ 1 は 0 未満です。
例
次の例では、部分文字列の末尾から部分文字列の先頭まで、部分文字列内の文字のすべての出現箇所のインデックスを検索します。
// Sample for String::LastIndexOf(Char, Int32, Int32)
using namespace System;
int main()
{
String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
String^ str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
int count;
int end;
start = str->Length - 1;
end = start / 2 - 1;
Console::WriteLine( "All occurrences of 't' from position {0} to {1}.", start, end );
Console::WriteLine( "\n{0}\n{1}\n{2}", br1, br2, str );
Console::Write( "The letter 't' occurs at position(s): " );
count = 0;
at = 0;
while ( (start > -1) && (at > -1) )
{
count = start - end; //Count must be within the substring.
at = str->LastIndexOf( 't', start, count );
if ( at > -1 )
{
Console::Write( " {0} ", at );
start = at - 1;
}
}
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33
*/
// Sample for String.LastIndexOf(Char, Int32, Int32)
using System;
class Sample {
public static void Main() {
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
string str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
int count;
int end;
start = str.Length-1;
end = start/2 - 1;
Console.WriteLine("All occurrences of 't' from position {0} to {1}.", start, end);
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The letter 't' occurs at position(s): ");
count = 0;
at = 0;
while((start > -1) && (at > -1))
{
count = start - end; //Count must be within the substring.
at = str.LastIndexOf('t', start, count);
if (at > -1)
{
Console.Write("{0} ", at);
start = at - 1;
}
}
Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33
*/
// Sample for String.LastIndexOf(Char, Int32, Int32)
open System
let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."
let mutable start = str.Length-1
let last = start / 2 - 1
printfn $"All occurrences of 't' from position {start} to {last}."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The letter 't' occurs at position(s): "
let mutable at = 0
while (start > -1) && (at > -1) do
let count = start - last //Count must be within the substring.
at <- str.LastIndexOf('t', start, count)
if at > -1 then
printf $"{at} "
start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 't' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33
*)
' Sample for String.LastIndexOf(Char, Int32, Int32)
_
Class Sample
Public Shared Sub Main()
Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
Dim str As String = "Now is the time for all good men to come to the aid of their party."
Dim start As Integer
Dim at As Integer
Dim count As Integer
Dim [end] As Integer
start = str.Length - 1
[end] = start / 2 - 1
Console.WriteLine("All occurrences of 't' from position {0} to {1}.", start, [end])
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
Console.Write("The letter 't' occurs at position(s): ")
count = 0
at = 0
While start > - 1 And at > - 1
count = start - [end] 'Count must be within the substring.
at = str.LastIndexOf("t"c, start, count)
If at > - 1 Then
Console.Write("{0} ", at)
start = at - 1
End If
End While
Console.Write("{0}{0}{0}", Environment.NewLine)
End Sub
End Class
'
'This example produces the following results:
'All occurrences of 't' from position 66 to 32.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The letter 't' occurs at position(s): 64 55 44 41 33
'
'
注釈
インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。
このメソッドは、startIndex
文字位置で検索を開始し、value
が見つかるか、count
文字位置が調べられるまで、このインスタンスの先頭に戻ります。 たとえば、startIndex
が Length - 1 の場合、メソッドは文字列の最後の文字から後方 count
文字を検索します。 検索では大文字と小文字が区別されます。
このメソッドは序数 (カルチャに依存しない) 検索を実行します。この検索では、Unicode スカラー値が同じ場合にのみ、文字が別の文字と同等と見なされます。 カルチャに依存する検索を実行するには、CompareInfo.LastIndexOf メソッドを使用します。ここで、合字 "Æ" (U+00C6) などの事前計算済み文字を表す Unicode スカラー値は、カルチャに応じて、"AE" (U+0041、U+0045) などの正しいシーケンス内の文字のコンポーネントの出現と同等と見なされる場合があります。
こちらもご覧ください
適用対象
LastIndexOf(String, StringComparison)
現在の String オブジェクト内で指定した文字列が最後に出現した位置の 0 から始まるインデックスを報告します。 パラメーターは、指定した文字列に使用する検索の種類を指定します。
public:
int LastIndexOf(System::String ^ value, StringComparison comparisonType);
public int LastIndexOf (string value, StringComparison comparisonType);
member this.LastIndexOf : string * StringComparison -> int
Public Function LastIndexOf (value As String, comparisonType As StringComparison) As Integer
パラメーター
- value
- String
シークする文字列。
- comparisonType
- StringComparison
検索の規則を指定する列挙値の 1 つ。
戻り値
その文字列が見つかった場合は、value
パラメーターの 0 から始まる開始インデックス位置。見つからない場合は -1。
例外
value
は null
です。
comparisonType
は有効な StringComparison 値ではありません。
例
次の例では、StringComparison 列挙型の異なる値を使用して、別の文字列内で文字列が最後に出現する箇所を検索する、LastIndexOf メソッドの 3 つのオーバーロードを示します。
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
using System;
using System.Threading;
using System.Globalization;
class Sample
{
public static void Main()
{
string intro = "Find the last occurrence of a character using different " +
"values of StringComparison.";
string resultFmt = "Comparison: {0,-28} Location: {1,3}";
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
string CapitalAWithRing = "\u00c5";
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
string cat = "A Cheshire c" + "\u0061\u030a" + "t";
int loc = 0;
StringComparison[] scValues = {
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
StringComparison.OrdinalIgnoreCase };
// Clear the screen and display an introduction.
Console.Clear();
Console.WriteLine(intro);
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("The current culture is \"{0}\" - {1}.",
Thread.CurrentThread.CurrentCulture.Name,
Thread.CurrentThread.CurrentCulture.DisplayName);
// Display the string to search for and the string to search.
Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"",
CapitalAWithRing, cat);
Console.WriteLine();
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
Console.WriteLine("Part 1: Start index and count are specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion. Specify the
// start index.
Console.WriteLine("\nPart 2: Start index is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, sc);
Console.WriteLine(resultFmt, sc, loc);
}
}
}
/*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*/
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
open System
open System.Threading
open System.Globalization
let intro = "Find the last occurrence of a character using different values of StringComparison."
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let CapitalAWithRing = "\u00c5"
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues =
[| StringComparison.CurrentCulture
StringComparison.CurrentCultureIgnoreCase
StringComparison.InvariantCulture
StringComparison.InvariantCultureIgnoreCase
StringComparison.Ordinal
StringComparison.OrdinalIgnoreCase |]
// Clear the screen and display an introduction.
Console.Clear()
printfn $"{intro}"
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."
// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
printfn "Part 1: Start index and count are specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*)
' This code example demonstrates the
' System.String.LastIndexOf(String, ..., StringComparison) methods.
Imports System.Threading
Imports System.Globalization
Class Sample
Public Shared Sub Main()
Dim intro As String = "Find the last occurrence of a character using different " & _
"values of StringComparison."
Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
' Define a string to search for.
' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
Dim CapitalAWithRing As String = "Å"
' Define a string to search.
' The result of combining the characters LATIN SMALL LETTER A and COMBINING
' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
Dim cat As String = "A Cheshire c" & "å" & "t"
Dim loc As Integer = 0
Dim scValues As StringComparison() = { _
StringComparison.CurrentCulture, _
StringComparison.CurrentCultureIgnoreCase, _
StringComparison.InvariantCulture, _
StringComparison.InvariantCultureIgnoreCase, _
StringComparison.Ordinal, _
StringComparison.OrdinalIgnoreCase }
Dim sc As StringComparison
' Clear the screen and display an introduction.
Console.Clear()
Console.WriteLine(intro)
' Display the current culture because culture affects the result. For example,
' try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
Console.WriteLine("The current culture is ""{0}"" - {1}.", _
Thread.CurrentThread.CurrentCulture.Name, _
Thread.CurrentThread.CurrentCulture.DisplayName)
' Display the string to search for and the string to search.
Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
CapitalAWithRing, cat)
Console.WriteLine()
' Note that in each of the following searches, we look for
' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
' the string was not found.
' Search using different values of StringComparsion. Specify the start
' index and count.
Console.WriteLine("Part 1: Start index and count are specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion. Specify the
' start index.
Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion.
Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
End Sub
End Class
'
'Note: This code example was executed on a console whose user interface
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the last occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
注釈
インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。
comparisonType
パラメーターは、次を使用して value
パラメーターを検索するように指定します。
- 現在のカルチャまたはインバリアント カルチャ。
- 大文字と小文字を区別する検索または大文字と小文字を区別しない検索。
- 単語または序数の比較規則。
検索は、このインスタンスの最後の文字位置から始まり、value
が見つかるか、最初の文字位置が調べられるまで先頭に向かって進みます。
注意 (呼び出し元)
文字セットには無視できる文字が含まれます。これは、言語的またはカルチャに依存する比較を実行するときに考慮されない文字です。 カルチャに依存する検索 (つまり、options
が Ordinal または OrdinalIgnoreCaseでない場合) では、value
に無視できる文字が含まれている場合、結果はその文字を削除して検索するのと同じです。
次の例では、LastIndexOf(String, StringComparison) メソッドを使用して、2 つの文字列で 2 つの部分文字列 (ソフト ハイフンの後に "n"、ソフト ハイフンの後に "m") を検索します。 ソフト ハイフンを含む文字列は 1 つだけです。 この例が .NET Framework 4 以降で実行されている場合、ソフト ハイフンは無視できる文字であるため、カルチャに依存する検索では、ソフト ハイフンが検索文字列に含まれていない場合と同じ値が返されます。 ただし、序数検索では、1 つの文字列でソフト ハイフンが正常に検出され、2 番目の文字列に含まれていないことが報告されます。
string s1 = "ani\u00ADmal";
string s2 = "animal";
Console.WriteLine("Culture-sensitive comparison:");
// Use culture-sensitive comparison to find the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf("\u00ADn", StringComparison.CurrentCulture));
Console.WriteLine(s2.LastIndexOf("\u00ADn", StringComparison.CurrentCulture));
// Use culture-sensitive comparison to find the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf("\u00ADm", StringComparison.CurrentCulture));
Console.WriteLine(s2.LastIndexOf("\u00ADm", StringComparison.CurrentCulture));
Console.WriteLine("Ordinal comparison:");
// Use ordinal comparison to find the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf("\u00ADn", StringComparison.Ordinal));
Console.WriteLine(s2.LastIndexOf("\u00ADn", StringComparison.Ordinal));
// Use ordinal comparison to find the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf("\u00ADm", StringComparison.Ordinal));
Console.WriteLine(s2.LastIndexOf("\u00ADm", StringComparison.Ordinal));
// The example displays the following output:
//
// Culture-sensitive comparison:
// 1
// 1
// 4
// 3
// Ordinal comparison:
// -1
// -1
// 3
// -1
open System
let s1 = "ani\u00ADmal"
let s2 = "animal"
printfn "Culture-sensitive comparison:"
// Use culture-sensitive comparison to find the last soft hyphen followed by "n".
printfn $"""{s1.LastIndexOf("\u00ADn", StringComparison.CurrentCulture)}"""
printfn $"""{s2.LastIndexOf("\u00ADn", StringComparison.CurrentCulture)}"""
// Use culture-sensitive comparison to find the last soft hyphen followed by "m".
printfn $"""{s1.LastIndexOf("\u00ADm", StringComparison.CurrentCulture)}"""
printfn $"""{s2.LastIndexOf("\u00ADm", StringComparison.CurrentCulture)}"""
printfn "Ordinal comparison:"
// Use ordinal comparison to find the last soft hyphen followed by "n".
printfn $"""{s1.LastIndexOf("\u00ADn", StringComparison.Ordinal)}"""
printfn $"""{s2.LastIndexOf("\u00ADn", StringComparison.Ordinal)}"""
// Use ordinal comparison to find the last soft hyphen followed by "m".
printfn $"""{s1.LastIndexOf("\u00ADm", StringComparison.Ordinal)}"""
printfn $"""{s2.LastIndexOf("\u00ADm", StringComparison.Ordinal)}"""
// The example displays the following output:
//
// Culture-sensitive comparison:
// 1
// 1
// 4
// 3
// Ordinal comparison:
// -1
// -1
// 3
// -1
Dim softHyphen As String = ChrW(&HAD)
Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"
Console.WriteLine("Culture-sensitive comparison:")
' Use culture-sensitive comparison to find the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf(softHyphen + "n", StringComparison.CurrentCulture))
Console.WriteLine(s2.LastIndexOf(softHyphen + "n", StringComparison.CurrentCulture))
' Use culture-sensitive comparison to find the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf(softHyphen + "m", StringComparison.CurrentCulture))
Console.WriteLine(s2.LastIndexOf(softHyphen + "m", StringComparison.CurrentCulture))
Console.WriteLine("Ordinal comparison:")
' Use ordinal comparison to find the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf(softHyphen + "n", StringComparison.Ordinal))
Console.WriteLine(s2.LastIndexOf(softHyphen + "n", StringComparison.Ordinal))
' Use ordinal comparison to find the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf(softHyphen + "m", StringComparison.Ordinal))
Console.WriteLine(s2.LastIndexOf(softHyphen + "m", StringComparison.Ordinal))
' The example displays the following output:
'
' Culture-sensitive comparison:
' 1
' 1
' 4
' 3
' Ordinal comparison:
' -1
' -1
' 3
' -1
適用対象
LastIndexOf(String, Int32, StringComparison)
現在の String オブジェクト内で指定した文字列が最後に出現した位置の 0 から始まるインデックスを報告します。 検索は指定した文字位置から開始し、文字列の先頭に向かって後方に進みます。 パラメーターは、指定した文字列を検索するときに実行する比較の種類を指定します。
public:
int LastIndexOf(System::String ^ value, int startIndex, StringComparison comparisonType);
public int LastIndexOf (string value, int startIndex, StringComparison comparisonType);
member this.LastIndexOf : string * int * StringComparison -> int
Public Function LastIndexOf (value As String, startIndex As Integer, comparisonType As StringComparison) As Integer
パラメーター
- value
- String
シークする文字列。
- startIndex
- Int32
検索開始位置。 検索は、startIndex
からこのインスタンスの先頭に進みます。
- comparisonType
- StringComparison
検索の規則を指定する列挙値の 1 つ。
戻り値
その文字列が見つかった場合は、value
パラメーターの 0 から始まる開始インデックス位置。見つからない場合、または現在のインスタンスが Empty等しい場合は -1。
例外
value
は null
です。
現在のインスタンスが Empty等しくなく、startIndex
が 0 より小さいか、現在のインスタンスの長さを超えています。
-又は-
現在のインスタンスは Emptyに等しく、startIndex
は -1 未満か、0 より大きい値です。
comparisonType
は有効な StringComparison 値ではありません。
例
次の例では、StringComparison 列挙型の異なる値を使用して、別の文字列内で文字列が最後に出現する箇所を検索する、LastIndexOf メソッドの 3 つのオーバーロードを示します。
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
using System;
using System.Threading;
using System.Globalization;
class Sample
{
public static void Main()
{
string intro = "Find the last occurrence of a character using different " +
"values of StringComparison.";
string resultFmt = "Comparison: {0,-28} Location: {1,3}";
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
string CapitalAWithRing = "\u00c5";
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
string cat = "A Cheshire c" + "\u0061\u030a" + "t";
int loc = 0;
StringComparison[] scValues = {
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
StringComparison.OrdinalIgnoreCase };
// Clear the screen and display an introduction.
Console.Clear();
Console.WriteLine(intro);
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("The current culture is \"{0}\" - {1}.",
Thread.CurrentThread.CurrentCulture.Name,
Thread.CurrentThread.CurrentCulture.DisplayName);
// Display the string to search for and the string to search.
Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"",
CapitalAWithRing, cat);
Console.WriteLine();
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
Console.WriteLine("Part 1: Start index and count are specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion. Specify the
// start index.
Console.WriteLine("\nPart 2: Start index is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, sc);
Console.WriteLine(resultFmt, sc, loc);
}
}
}
/*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*/
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
open System
open System.Threading
open System.Globalization
let intro = "Find the last occurrence of a character using different values of StringComparison."
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let CapitalAWithRing = "\u00c5"
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues =
[| StringComparison.CurrentCulture
StringComparison.CurrentCultureIgnoreCase
StringComparison.InvariantCulture
StringComparison.InvariantCultureIgnoreCase
StringComparison.Ordinal
StringComparison.OrdinalIgnoreCase |]
// Clear the screen and display an introduction.
Console.Clear()
printfn $"{intro}"
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."
// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
printfn "Part 1: Start index and count are specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*)
' This code example demonstrates the
' System.String.LastIndexOf(String, ..., StringComparison) methods.
Imports System.Threading
Imports System.Globalization
Class Sample
Public Shared Sub Main()
Dim intro As String = "Find the last occurrence of a character using different " & _
"values of StringComparison."
Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
' Define a string to search for.
' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
Dim CapitalAWithRing As String = "Å"
' Define a string to search.
' The result of combining the characters LATIN SMALL LETTER A and COMBINING
' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
Dim cat As String = "A Cheshire c" & "å" & "t"
Dim loc As Integer = 0
Dim scValues As StringComparison() = { _
StringComparison.CurrentCulture, _
StringComparison.CurrentCultureIgnoreCase, _
StringComparison.InvariantCulture, _
StringComparison.InvariantCultureIgnoreCase, _
StringComparison.Ordinal, _
StringComparison.OrdinalIgnoreCase }
Dim sc As StringComparison
' Clear the screen and display an introduction.
Console.Clear()
Console.WriteLine(intro)
' Display the current culture because culture affects the result. For example,
' try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
Console.WriteLine("The current culture is ""{0}"" - {1}.", _
Thread.CurrentThread.CurrentCulture.Name, _
Thread.CurrentThread.CurrentCulture.DisplayName)
' Display the string to search for and the string to search.
Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
CapitalAWithRing, cat)
Console.WriteLine()
' Note that in each of the following searches, we look for
' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
' the string was not found.
' Search using different values of StringComparsion. Specify the start
' index and count.
Console.WriteLine("Part 1: Start index and count are specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion. Specify the
' start index.
Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion.
Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
End Sub
End Class
'
'Note: This code example was executed on a console whose user interface
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the last occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
注釈
インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。
検索は startIndex
文字位置から始まり、value
が見つかるか、最初の文字位置が調べられるまで後方に進みます。 たとえば、startIndex
が Length - 1 の場合、メソッドは文字列の最後の文字から先頭までのすべての文字を検索します。
comparisonType
パラメーターは、現在のカルチャまたはインバリアント カルチャ、大文字と小文字を区別しない検索、および単語または序数の比較規則を使用して、value
パラメーターを検索するように指定します。
注意 (呼び出し元)
文字セットには無視できる文字が含まれます。これは、言語的またはカルチャに依存する比較を実行するときに考慮されない文字です。 カルチャに依存する検索 (つまり、comparisonType
が Ordinal または OrdinalIgnoreCaseでない場合) では、value
に無視できる文字が含まれている場合、結果はその文字を削除して検索するのと同じです。
次の例では、LastIndexOf(String, Int32, StringComparison) メソッドを使用して、ソフト ハイフン (U+00AD) の後に "m" が続き、2 つの文字列の最後の "m" から始まる位置を検索します。 必要な部分文字列を含む文字列は 1 つだけです。 この例が .NET Framework 4 以降で実行されている場合、どちらの場合も、ソフト ハイフンは無視できる文字であるため、カルチャに依存する比較を実行すると、メソッドは文字列内の "m" のインデックスを返します。 ソフト ハイフンの後に "m" が続く最初の文字列の場合、メソッドはソフト ハイフンのインデックスではなく、"m" のインデックスを返します。 メソッドは、序数比較を実行する場合にのみ、最初の文字列のソフト ハイフンのインデックスを返します。
string searchString = "\u00ADm";
string s1 = "ani\u00ADmal";
string s2 = "animal";
int position;
position = s1.LastIndexOf('m');
if (position >= 0)
{
Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.CurrentCulture));
Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.Ordinal));
}
position = s2.LastIndexOf('m');
if (position >= 0)
{
Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.CurrentCulture));
Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.Ordinal));
}
// The example displays the following output:
//
// 4
// 3
// 3
// -1
let searchString = "\u00ADm"
let s1 = "ani\u00ADmal"
let s2 = "animal"
let position = s1.LastIndexOf 'm'
if position >= 0 then
printfn $"{s1.LastIndexOf(searchString, position, StringComparison.CurrentCulture)}"
printfn $"{s1.LastIndexOf(searchString, position, StringComparison.Ordinal)}"
let position = s2.LastIndexOf 'm'
if position >= 0 then
printfn $"{s2.LastIndexOf(searchString, position, StringComparison.CurrentCulture)}"
printfn $"{s2.LastIndexOf(searchString, position, StringComparison.Ordinal)}"
// The example displays the following output:
//
// 4
// 3
// 3
// -1
Dim searchString As String = ChrW(&HAD) + "m"
Dim s1 As String = "ani" + ChrW(&HAD) + "mal"
Dim s2 As String = "animal"
Dim position As Integer
position = s1.LastIndexOf("m"c)
If position >= 0 Then
Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.CurrentCulture))
Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.Ordinal))
End If
position = s2.LastIndexOf("m"c)
If position >= 0 Then
Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.CurrentCulture))
Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.Ordinal))
End If
' The example displays the following output:
'
' 4
' 3
' 3
' -1
適用対象
LastIndexOf(Char, Int32)
指定した Unicode 文字がこのインスタンス内で最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は指定した文字位置から開始し、文字列の先頭に向かって後方に進みます。
public:
int LastIndexOf(char value, int startIndex);
public int LastIndexOf (char value, int startIndex);
member this.LastIndexOf : char * int -> int
Public Function LastIndexOf (value As Char, startIndex As Integer) As Integer
パラメーター
- value
- Char
シークする Unicode 文字。
- startIndex
- Int32
検索の開始位置。 検索は、startIndex
からこのインスタンスの先頭に進みます。
戻り値
その文字が見つかった場合は value
の 0 から始まるインデックス位置。見つからない場合、または現在のインスタンスが Empty等しい場合は -1。
例外
現在のインスタンスが Empty等しくなく、startIndex
が 0 未満であるか、このインスタンスの長さ以上です。
例
次の例では、文字列の末尾から文字列の先頭まで、文字列内のすべての出現箇所のインデックスを検索します。
// Sample for String::LastIndexOf(Char, Int32)
using namespace System;
int main()
{
String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
String^ str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
start = str->Length - 1;
Console::WriteLine( "All occurrences of 't' from position {0} to 0.", start );
Console::WriteLine( "{0}\n{1}\n{2}\n", br1, br2, str );
Console::Write( "The letter 't' occurs at position(s): " );
at = 0;
while ( (start > -1) && (at > -1) )
{
at = str->LastIndexOf( 't', start );
if ( at > -1 )
{
Console::Write( " {0} ", at );
start = at - 1;
}
}
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33 11 7
*/
// Sample for String.LastIndexOf(Char, Int32)
using System;
class Sample {
public static void Main() {
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
string str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
start = str.Length-1;
Console.WriteLine("All occurrences of 't' from position {0} to 0.", start);
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The letter 't' occurs at position(s): ");
at = 0;
while((start > -1) && (at > -1))
{
at = str.LastIndexOf('t', start);
if (at > -1)
{
Console.Write("{0} ", at);
start = at - 1;
}
}
Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33 11 7
*/
// Sample for String.LastIndexOf(Char, Int32)
open System
let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."
let mutable start = str.Length - 1
printfn $"All occurrences of 't' from position {start} to 0."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The letter 't' occurs at position(s): "
let mutable at = 0
while (start > -1) && (at > -1) do
at <- str.LastIndexOf('t', start)
if at > -1 then
printf $"{at} "
start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 't' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33 11 7
*)
' Sample for String.LastIndexOf(Char, Int32)
Imports System
_
Class Sample
Public Shared Sub Main()
Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
Dim str As String = "Now is the time for all good men to come to the aid of their party."
Dim start As Integer
Dim at As Integer
start = str.Length - 1
Console.WriteLine("All occurrences of 't' from position {0} to 0.", start)
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
Console.Write("The letter 't' occurs at position(s): ")
at = 0
While start > - 1 And at > - 1
at = str.LastIndexOf("t"c, start)
If at > - 1 Then
Console.Write("{0} ", at)
start = at - 1
End If
End While
Console.Write("{0}{0}{0}", Environment.NewLine)
End Sub
End Class
'
'This example produces the following results:
'All occurrences of 't' from position 66 to 0.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The letter 't' occurs at position(s): 64 55 44 41 33 11 7
'
注釈
インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。 このメソッドは、このインスタンスの startIndex
文字位置で検索を開始し、value
が見つかるか、最初の文字位置が調べられるまで、現在のインスタンスの先頭に戻ります。 たとえば、startIndex
が Length - 1 の場合、メソッドは文字列の最後の文字から先頭までのすべての文字を検索します。 検索では大文字と小文字が区別されます。
このメソッドは序数 (カルチャに依存しない) 検索を実行します。この検索では、Unicode スカラー値が同じ場合にのみ、文字が別の文字と同等と見なされます。 カルチャに依存する検索を実行するには、CompareInfo.LastIndexOf メソッドを使用します。ここで、合字 "Æ" (U+00C6) などの事前計算済み文字を表す Unicode スカラー値は、カルチャに応じて、"AE" (U+0041、U+0045) などの正しいシーケンス内の文字のコンポーネントの出現と同等と見なされる場合があります。
こちらもご覧ください
適用対象
LastIndexOf(String)
このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。
public:
int LastIndexOf(System::String ^ value);
public int LastIndexOf (string value);
member this.LastIndexOf : string -> int
Public Function LastIndexOf (value As String) As Integer
パラメーター
- value
- String
シークする文字列。
戻り値
その文字列が見つかった場合は value
の 0 から始まる開始インデックス位置。見つからない場合は -1。
例外
value
は null
です。
例
次の例では、タグが文字列の開始と終了の場合に、文字列から開始と終了の HTML タグを削除します。 文字列が終わり角かっこ (">") で終わる場合、この例では、LastIndexOf メソッドを使用して終了タグの先頭を見つけます。
using System;
public class Example
{
public static void Main()
{
string[] strSource = { "<b>This is bold text</b>", "<H1>This is large Text</H1>",
"<b><i><font color=green>This has multiple tags</font></i></b>",
"<b>This has <i>embedded</i> tags.</b>",
"This line ends with a greater than symbol and should not be modified>" };
// Strip HTML start and end tags from each string if they are present.
foreach (string s in strSource)
{
Console.WriteLine("Before: " + s);
string item = s;
// Use EndsWith to find a tag at the end of the line.
if (item.Trim().EndsWith(">"))
{
// Locate the opening tag.
int endTagStartPosition = item.LastIndexOf("</");
// Remove the identified section, if it is valid.
if (endTagStartPosition >= 0 )
item = item.Substring(0, endTagStartPosition);
// Use StartsWith to find the opening tag.
if (item.Trim().StartsWith("<"))
{
// Locate the end of opening tab.
int openTagEndPosition = item.IndexOf(">");
// Remove the identified section, if it is valid.
if (openTagEndPosition >= 0)
item = item.Substring(openTagEndPosition + 1);
}
}
// Display the trimmed string.
Console.WriteLine("After: " + item);
Console.WriteLine();
}
}
}
// The example displays the following output:
// Before: <b>This is bold text</b>
// After: This is bold text
//
// Before: <H1>This is large Text</H1>
// After: This is large Text
//
// Before: <b><i><font color=green>This has multiple tags</font></i></b>
// After: <i><font color=green>This has multiple tags</font></i>
//
// Before: <b>This has <i>embedded</i> tags.</b>
// After: This has <i>embedded</i> tags.
//
// Before: This line ends with a greater than symbol and should not be modified>
// After: This line ends with a greater than symbol and should not be modified>
let strSource =
[| "<b>This is bold text</b>"; "<H1>This is large Text</H1>"
"<b><i><font color=green>This has multiple tags</font></i></b>"
"<b>This has <i>embedded</i> tags.</b>"
"This line ends with a greater than symbol and should not be modified>" |]
// Strip HTML start and end tags from each string if they are present.
for s in strSource do
printfn $"Before: {s}"
let mutable item = s
// Use EndsWith to find a tag at the end of the line.
if item.Trim().EndsWith ">" then
// Locate the opening tag.
let endTagStartPosition = item.LastIndexOf "</"
// Remove the identified section, if it is valid.
if endTagStartPosition >= 0 then
item <- item.Substring(0, endTagStartPosition)
// Use StartsWith to find the opening tag.
if item.Trim().StartsWith "<" then
// Locate the end of opening tab.
let openTagEndPosition = item.IndexOf ">"
// Remove the identified section, if it is valid.
if openTagEndPosition >= 0 then
item <- item.Substring(openTagEndPosition + 1)
// Display the trimmed string.
printfn "After: {item}"
printfn ""
// The example displays the following output:
// Before: <b>This is bold text</b>
// After: This is bold text
//
// Before: <H1>This is large Text</H1>
// After: This is large Text
//
// Before: <b><i><font color=green>This has multiple tags</font></i></b>
// After: <i><font color=green>This has multiple tags</font></i>
//
// Before: <b>This has <i>embedded</i> tags.</b>
// After: This has <i>embedded</i> tags.
//
// Before: This line ends with a greater than symbol and should not be modified>
// After: This line ends with a greater than symbol and should not be modified>
Module Example
Public Sub Main()
Dim strSource As String() = { "<b>This is bold text</b>", _
"<H1>This is large Text</H1>", _
"<b><i><font color=green>This has multiple tags</font></i></b>", _
"<b>This has <i>embedded</i> tags.</b>", _
"This line ends with a greater than symbol and should not be modified>" }
' Strip HTML start and end tags from each string if they are present.
For Each s As String In strSource
Console.WriteLine("Before: " + s)
' Use EndsWith to find a tag at the end of the line.
If s.Trim().EndsWith(">") Then
' Locate the opening tag.
Dim endTagStartPosition As Integer = s.LastIndexOf("</")
' Remove the identified section if it is valid.
If endTagStartPosition >= 0 Then
s = s.Substring(0, endTagStartPosition)
End If
' Use StartsWith to find the opening tag.
If s.Trim().StartsWith("<") Then
' Locate the end of opening tab.
Dim openTagEndPosition As Integer = s.IndexOf(">")
' Remove the identified section if it is valid.
If openTagEndPosition >= 0 Then
s = s.Substring(openTagEndPosition + 1)
End If
End If
End If
' Display the trimmed string.
Console.WriteLine("After: " + s)
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' Before: <b>This is bold text</b>
' After: This is bold text
'
' Before: <H1>This is large Text</H1>
' After: This is large Text
'
' Before: <b><i><font color=green>This has multiple tags</font></i></b>
' After: <i><font color=green>This has multiple tags</font></i>
'
' Before: <b>This has <i>embedded</i> tags.</b>
' After: This has <i>embedded</i> tags.
'
' Before: This line ends with a greater than symbol and should not be modified>
' After: This line ends with a greater than symbol and should not be modified>
注釈
インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。
検索は、このインスタンスの最後の文字位置から始まり、value
が見つかるか、最初の文字位置が調べられるまで先頭に向かって進みます。
このメソッドは、現在のカルチャを使用して単語 (大文字と小文字が区別され、カルチャに依存する) 検索を実行します。
文字セットには無視できる文字が含まれます。これは、言語的またはカルチャに依存する比較を実行するときに考慮されない文字です。 カルチャに依存する検索では、value
に無視できる文字が含まれている場合、その文字を削除した場合の検索と同じ結果になります。
次の例では、LastIndexOf(String) メソッドを使用して、2 つの文字列で 2 つの部分文字列 (ソフト ハイフンの後に "n" とソフト ハイフンの後に "m") を検索します。 ソフト ハイフンを含む文字列は 1 つだけです。 この例が .NET Framework 4 以降で実行されている場合、いずれの場合も、ソフト ハイフンは無視できる文字であるため、結果はソフト ハイフンが value
に含まれていない場合と同じです。
string s1 = "ani\u00ADmal";
string s2 = "animal";
// Find the index of the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf("\u00ADn"));
Console.WriteLine(s2.LastIndexOf("\u00ADn"));
// Find the index of the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf("\u00ADm"));
Console.WriteLine(s2.LastIndexOf("\u00ADm"));
// The example displays the following output:
//
// 1
// 1
// 4
// 3
let s1 = "ani\u00ADmal"
let s2 = "animal"
// Find the index of the last soft hyphen followed by "n".
printfn $"""{s1.LastIndexOf "\u00ADn"}"""
printfn $"""{s2.LastIndexOf "\u00ADn"}"""
// Find the index of the last soft hyphen followed by "m".
printfn $"""{s1.LastIndexOf "\u00ADm"}"""
printfn $"""{s2.LastIndexOf "\u00ADm"}"""
// The example displays the following output:
//
// 1
// 1
// 4
// 3
Dim softHyphen As String = ChrW(&HAD)
Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"
' Find the index of the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf(softHyphen + "n"))
Console.WriteLine(s2.LastIndexOf(softHyphen + "n"))
' Find the index of the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf(softHyphen + "m"))
Console.WriteLine(s2.LastIndexOf(softHyphen + "m"))
' The example displays the following output:
'
' 1
' 1
' 4
' 3
注意 (呼び出し元)
文字列を使用するためのベスト プラクティス comparisonType
パラメーターの値を CurrentCulture して明示的に意図を通知します。 言語に対応した比較が必要ない場合は、Ordinalの使用を検討してください。
こちらもご覧ください
適用対象
LastIndexOf(Char)
指定した Unicode 文字がこのインスタンス内で最後に出現した位置の、0 から始まるインデックス位置を報告します。
public:
int LastIndexOf(char value);
public int LastIndexOf (char value);
member this.LastIndexOf : char -> int
Public Function LastIndexOf (value As Char) As Integer
パラメーター
- value
- Char
シークする Unicode 文字。
戻り値
その文字が見つかった場合は value
の 0 から始まるインデックス位置。見つからない場合は -1。
例
次の例では、LastIndexOf(Char) メソッドを使用して文字列内の最後のディレクトリ区切り文字を検索し、文字列のファイル名を抽出する ExtractFilename
メソッドを定義します。 ファイルが存在する場合、メソッドはパスのないファイル名を返します。
using System;
using System.IO;
public class TestLastIndexOf
{
public static void Main()
{
string filename;
filename = ExtractFilename(@"C:\temp\");
Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
filename = ExtractFilename(@"C:\temp\delegate.txt");
Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
filename = ExtractFilename("delegate.txt");
Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
filename = ExtractFilename(@"C:\temp\notafile.txt");
Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
}
public static string ExtractFilename(string filepath)
{
// If path ends with a "\", it's a path only so return String.Empty.
if (filepath.Trim().EndsWith(@"\"))
return String.Empty;
// Determine where last backslash is.
int position = filepath.LastIndexOf('\\');
// If there is no backslash, assume that this is a filename.
if (position == -1)
{
// Determine whether file exists in the current directory.
if (File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath))
return filepath;
else
return String.Empty;
}
else
{
// Determine whether file exists using filepath.
if (File.Exists(filepath))
// Return filename without file path.
return filepath.Substring(position + 1);
else
return String.Empty;
}
}
}
open System
open System.IO
let extractFilename (filepath: string) =
// If path ends with a "\", it's a path only so return String.Empty.
if filepath.Trim().EndsWith @"\" then
String.Empty
else
// Determine where last backslash is.
let position = filepath.LastIndexOf '\\'
// If there is no backslash, assume that this is a filename.
if position = -1 then
// Determine whether file exists in the current directory.
if File.Exists(Environment.CurrentDirectory + string Path.DirectorySeparatorChar + filepath) then
filepath
else
String.Empty
else
// Determine whether file exists using filepath.
if File.Exists filepath then
// Return filename without file path.
filepath.Substring(position + 1)
else
String.Empty
do
let filename = extractFilename @"C:\temp\"
printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""
let filename = extractFilename @"C:\temp\delegate.txt"
printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""
let filename = extractFilename "delegate.txt"
printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""
let filename = extractFilename @"C:\temp\notafile.txt"
printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""
Imports System.IO
Public Module Test
Public Sub Main()
Dim filename As String
filename = ExtractFilename("C:\temp\")
Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
filename = ExtractFilename("C:\temp\delegate.txt")
Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
filename = ExtractFilename("delegate.txt")
Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
filename = ExtractFilename("C:\temp\notafile.txt")
Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
End Sub
Public Function ExtractFilename(filepath As String) As String
' If path ends with a "\", it's a path only so return String.Empty.
If filepath.Trim().EndsWith("\") Then Return String.Empty
' Determine where last backslash is.
Dim position As Integer = filepath.LastIndexOf("\"c)
' If there is no backslash, assume that this is a filename.
If position = -1 Then
' Determine whether file exists in the current directory.
If File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath) Then
Return filepath
Else
Return String.Empty
End If
Else
' Determine whether file exists using filepath.
If File.Exists(filepath) Then
' Return filename without file path.
Return filepath.Substring(position + 1)
Else
Return String.Empty
End If
End If
End Function
End Module
' The example displays the following output:
' delegate.txt
注釈
インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。
このメソッドは、このインスタンスの最後の文字位置で検索を開始し、value
が見つかるか、最初の文字位置が調べられるまで先頭に向かって進みます。 検索では大文字と小文字が区別されます。
このメソッドは序数 (カルチャに依存しない) 検索を実行します。この検索では、Unicode スカラー値が同じ場合にのみ、文字が別の文字と同等と見なされます。 カルチャに依存する検索を実行するには、CompareInfo.LastIndexOf メソッドを使用します。ここで、合字 "Æ" (U+00C6) などの事前計算済み文字を表す Unicode スカラー値は、カルチャに応じて、"AE" (U+0041、U+0045) などの正しいシーケンス内の文字のコンポーネントの出現と同等と見なされる場合があります。
こちらもご覧ください
適用対象
LastIndexOf(String, Int32)
このインスタンス内で指定した文字列が最後に出現した位置の、0 から始まるインデックス位置を報告します。 検索は指定した文字位置から開始し、文字列の先頭に向かって後方に進みます。
public:
int LastIndexOf(System::String ^ value, int startIndex);
public int LastIndexOf (string value, int startIndex);
member this.LastIndexOf : string * int -> int
Public Function LastIndexOf (value As String, startIndex As Integer) As Integer
パラメーター
- value
- String
シークする文字列。
- startIndex
- Int32
検索開始位置。 検索は、startIndex
からこのインスタンスの先頭に進みます。
戻り値
その文字列が見つかった場合は、value
の 0 から始まる開始インデックス位置。見つからない場合、または現在のインスタンスが Empty等しい場合は -1。
例外
value
は null
です。
現在のインスタンスが Empty等しくなく、startIndex
が 0 より小さいか、現在のインスタンスの長さを超えています。
-又は-
現在のインスタンスは Emptyに等しく、startIndex
は -1 未満か、0 より大きい値です。
例
次の例では、ターゲット文字列内の文字列のすべての出現箇所のインデックスを検索します。これは、ターゲット文字列の末尾からターゲット文字列の先頭まで動作します。
// Sample for String::LastIndexOf(String, Int32)
using namespace System;
int main()
{
String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
String^ str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
start = str->Length - 1;
Console::WriteLine( "All occurrences of 'he' from position {0} to 0.", start );
Console::WriteLine( "{0}\n{1}\n{2}\n", br1, br2, str );
Console::Write( "The string 'he' occurs at position(s): " );
at = 0;
while ( (start > -1) && (at > -1) )
{
at = str->LastIndexOf( "he", start );
if ( at > -1 )
{
Console::Write( " {0} ", at );
start = at - 1;
}
}
Console::WriteLine();
}
/*
This example produces the following results:
All occurrences of 'he' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45 8
*/
// Sample for String.LastIndexOf(String, Int32)
using System;
class Sample {
public static void Main() {
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
string str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
start = str.Length-1;
Console.WriteLine("All occurrences of 'he' from position {0} to 0.", start);
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The string 'he' occurs at position(s): ");
at = 0;
while((start > -1) && (at > -1))
{
at = str.LastIndexOf("he", start);
if (at > -1)
{
Console.Write("{0} ", at);
start = at - 1;
}
}
Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
This example produces the following results:
All occurrences of 'he' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45 8
*/
// Sample for String.LastIndexOf(String, Int32)
open System
let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."
let mutable start = str.Length - 1
printfn $"All occurrences of 'he' from position {start} to 0."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The string 'he' occurs at position(s): "
let mutable at = 0
while (start > -1) && (at > -1) do
at <- str.LastIndexOf("he", start)
if at > -1 then
printf $"{at} "
start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 'he' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45 8
*)
' Sample for String.LastIndexOf(String, Int32)
_
Class Sample
Public Shared Sub Main()
Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
Dim str As String = "Now is the time for all good men to come to the aid of their party."
Dim start As Integer
Dim at As Integer
'#3
start = str.Length - 1
Console.WriteLine("All occurrences of 'he' from position {0} to 0.", start)
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
Console.Write("The string 'he' occurs at position(s): ")
at = 0
While start > - 1 And at > - 1
at = str.LastIndexOf("he", start)
If at > - 1 Then
Console.Write("{0} ", at)
start = at - 1
End If
End While
Console.Write("{0}{0}{0}", Environment.NewLine)
End Sub
End Class
'
'This example produces the following results:
'All occurrences of 'he' from position 66 to 0.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The string 'he' occurs at position(s): 56 45 8
'
'
注釈
インデックス番号は 0 から始まります。 つまり、文字列の最初の文字はインデックス 0 で、最後の文字は Length - 1 です。
検索は、このインスタンスの startIndex
文字位置から始まり、value
が見つかるか、最初の文字位置が調べられるまで、先頭に向かって後方に進みます。 たとえば、startIndex
が Length - 1 の場合、メソッドは文字列の最後の文字から先頭までのすべての文字を検索します。
このメソッドは、現在のカルチャを使用して単語 (大文字と小文字が区別され、カルチャに依存する) 検索を実行します。
文字セットには無視できる文字が含まれます。これは、言語的またはカルチャに依存する比較を実行するときに考慮されない文字です。 カルチャに依存する検索では、value
に無視できる文字が含まれている場合、その文字を削除した場合の検索と同じ結果になります。 次の例では、LastIndexOf(String, Int32) メソッドを使用して、ソフト ハイフン (U+00AD) を含み、文字列の最後の "m" の前または末尾に含まれる部分文字列を検索します。 この例が .NET Framework 4 以降で実行されている場合、検索文字列内のソフト ハイフンが無視されるため、メソッドを呼び出してソフト ハイフンで構成される部分文字列を検索し、"m" は文字列内の "m" の位置を返し、それを呼び出してソフト ハイフンで構成される部分文字列を検索し、"n" は "n" の位置を返します。
int position = 0;
string s1 = "ani\u00ADmal";
string s2 = "animal";
// Find the index of the soft hyphen followed by "n".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s1.LastIndexOf("\u00ADn", position));
position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s2.LastIndexOf("\u00ADn", position));
// Find the index of the soft hyphen followed by "m".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s1.LastIndexOf("\u00ADm", position));
position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s2.LastIndexOf("\u00ADm", position));
// The example displays the following output:
//
// 'm' at position 4
// 1
// 'm' at position 3
// 1
// 'm' at position 4
// 4
// 'm' at position 3
// 3
let s1 = "ani\u00ADmal"
let s2 = "animal"
// Find the index of the soft hyphen followed by "n".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s1.LastIndexOf("\u00ADn", position)}"""
let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s2.LastIndexOf("\u00ADn", position)}"""
// Find the index of the soft hyphen followed by "m".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s1.LastIndexOf("\u00ADm", position)}"""
let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s2.LastIndexOf("\u00ADm", position)}"""
// The example displays the following output:
//
// 'm' at position 4
// 1
// 'm' at position 3
// 1
// 'm' at position 4
// 4
// 'm' at position 3
// 3
Dim position As Integer
Dim softHyphen As String = ChrW(&HAD)
Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"
' Find the index of the soft hyphen followed by "n".
position = s1.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s1.LastIndexOf(softHyphen + "n", position))
End If
position = s2.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s2.LastIndexOf(softHyphen + "n", position))
End If
' Find the index of the soft hyphen followed by "m".
position = s1.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s1.LastIndexOf(softHyphen + "m", position))
End If
position = s2.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s2.LastIndexOf(softHyphen + "m", position))
End If
' The example displays the following output:
'
' 'm' at position 4
' 1
' 'm' at position 3
' 1
' 'm' at position 4
' 4
' 'm' at position 3
' 3
注意 (呼び出し元)
文字列を使用するためのベスト プラクティス comparisonType
パラメーターの値を使用して LastIndexOf(String, Int32, StringComparison) メソッドオーバーロードを呼び出して、意図を明示的に通知 CurrentCulture。 言語に対応した比較が必要ない場合は、Ordinalの使用を検討してください。
こちらもご覧ください
適用対象
.NET