String.LastIndexOf 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
報告這個執行個體中指定之 Unicode 字元或字串最後一次出現時的所在索引 (以零為起始)。 如果在此執行個體中找不到該字元或字串,此方法會傳回 -1。
多載
LastIndexOf(String, Int32, Int32, StringComparison) |
回報這個執行個體中指定之字串最後一次出現時的所在索引 (以零為起始)。 搜尋會從指定的字元位置開始,然後反向朝字串開頭指定數目的字元位置進行。 參數會指定搜尋指定字串時要執行的比較類型。 |
LastIndexOf(String, Int32, StringComparison) |
報告目前 String 物件中指定之字串最後一次出現時的所在索引 (以零為起始)。 搜尋會從指定的字元位置開始,然後反向朝字串的開頭進行。 參數會指定搜尋指定字串時要執行的比較類型。 |
LastIndexOf(String, Int32, Int32) |
回報這個執行個體中指定之字串最後一次出現時的所在索引 (以零為起始)。 搜尋會從指定的字元位置開始,然後反向朝字串開頭指定數目的字元位置進行。 |
LastIndexOf(Char, Int32, Int32) |
報告這個執行個體的子字串中,指定的 Unicode 字元最後一次出現時的所在索引 (以零為起始)。 搜尋會從指定的字元位置開始,然後反向朝字串開頭指定數目的字元位置進行。 |
LastIndexOf(String, Int32) |
回報這個執行個體中指定之字串最後一次出現時的所在索引 (以零為起始)。 搜尋會從指定的字元位置開始,然後反向朝字串的開頭進行。 |
LastIndexOf(Char, Int32) |
報告這個執行個體中指定之 Unicode 字元最後一次出現時的所在索引 (以零為起始)。 搜尋會從指定的字元位置開始,然後反向朝字串的開頭進行。 |
LastIndexOf(String) |
回報這個執行個體中指定之字串最後一次出現時的所在索引 (以零為起始)。 |
LastIndexOf(Char) |
報告這個執行個體中指定之 Unicode 字元最後一次出現時的所在索引 (以零為起始)。 |
LastIndexOf(String, StringComparison) |
報告目前 String 物件中指定之字串最後一次出現時的所在索引 (以零為起始)。 參數會指定要用於指定字串的搜尋類型。 |
LastIndexOf(String, Int32, Int32, StringComparison)
回報這個執行個體中指定之字串最後一次出現時的所在索引 (以零為起始)。 搜尋會從指定的字元位置開始,然後反向朝字串開頭指定數目的字元位置進行。 參數會指定搜尋指定字串時要執行的比較類型。
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
其中一個列舉值,指定搜尋規則。
傳回
如果找到該字串,則為 value
參數以零為起始的索引位置,如果找不到該字串或者目前的執行個體等於 Empty,則為 -1。
例外狀況
value
為 null
。
count
為負。
-或-
目前的執行個體不等於 Empty,且 startIndex
為負。
-或-
目前的執行個體不等於 Empty,且 startIndex
大於這個執行個體的長度。
-或-
目前的執行個體不等於 Empty,且 startIndex
+ 1 - count
指定的位置不在此執行個體之內。
-或-
目前的執行個體等於 Empty,且 start
小於 -1 或大於零。
-或-
目前的執行個體等於 Empty,且 count
大於 1。
comparisonType
不是有效的 StringComparison 值。
範例
下列範例示範方法的 LastIndexOf 三個多載,這些多載會使用列舉的不同值 StringComparison ,尋找另一個字串內最後一個出現的字串。
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
using System;
using System.Threading;
using System.Globalization;
class Sample
{
public static void Main()
{
string intro = "Find the last occurrence of a character using different " +
"values of StringComparison.";
string resultFmt = "Comparison: {0,-28} Location: {1,3}";
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
string CapitalAWithRing = "\u00c5";
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
string cat = "A Cheshire c" + "\u0061\u030a" + "t";
int loc = 0;
StringComparison[] scValues = {
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
StringComparison.OrdinalIgnoreCase };
// Clear the screen and display an introduction.
Console.Clear();
Console.WriteLine(intro);
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("The current culture is \"{0}\" - {1}.",
Thread.CurrentThread.CurrentCulture.Name,
Thread.CurrentThread.CurrentCulture.DisplayName);
// Display the string to search for and the string to search.
Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"",
CapitalAWithRing, cat);
Console.WriteLine();
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
Console.WriteLine("Part 1: Start index and count are specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion. Specify the
// start index.
Console.WriteLine("\nPart 2: Start index is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, sc);
Console.WriteLine(resultFmt, sc, loc);
}
}
}
/*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*/
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
open System
open System.Threading
open System.Globalization
let intro = "Find the last occurrence of a character using different values of StringComparison."
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let CapitalAWithRing = "\u00c5"
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues =
[| StringComparison.CurrentCulture
StringComparison.CurrentCultureIgnoreCase
StringComparison.InvariantCulture
StringComparison.InvariantCultureIgnoreCase
StringComparison.Ordinal
StringComparison.OrdinalIgnoreCase |]
// Clear the screen and display an introduction.
Console.Clear()
printfn $"{intro}"
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."
// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
printfn "Part 1: Start index and count are specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*)
' This code example demonstrates the
' System.String.LastIndexOf(String, ..., StringComparison) methods.
Imports System.Threading
Imports System.Globalization
Class Sample
Public Shared Sub Main()
Dim intro As String = "Find the last occurrence of a character using different " & _
"values of StringComparison."
Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
' Define a string to search for.
' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
Dim CapitalAWithRing As String = "Å"
' Define a string to search.
' The result of combining the characters LATIN SMALL LETTER A and COMBINING
' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
Dim cat As String = "A Cheshire c" & "å" & "t"
Dim loc As Integer = 0
Dim scValues As StringComparison() = { _
StringComparison.CurrentCulture, _
StringComparison.CurrentCultureIgnoreCase, _
StringComparison.InvariantCulture, _
StringComparison.InvariantCultureIgnoreCase, _
StringComparison.Ordinal, _
StringComparison.OrdinalIgnoreCase }
Dim sc As StringComparison
' Clear the screen and display an introduction.
Console.Clear()
Console.WriteLine(intro)
' Display the current culture because culture affects the result. For example,
' try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
Console.WriteLine("The current culture is ""{0}"" - {1}.", _
Thread.CurrentThread.CurrentCulture.Name, _
Thread.CurrentThread.CurrentCulture.DisplayName)
' Display the string to search for and the string to search.
Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
CapitalAWithRing, cat)
Console.WriteLine()
' Note that in each of the following searches, we look for
' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
' the string was not found.
' Search using different values of StringComparsion. Specify the start
' index and count.
Console.WriteLine("Part 1: Start index and count are specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion. Specify the
' start index.
Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion.
Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
End Sub
End Class
'
'Note: This code example was executed on a console whose user interface
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the last occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
備註
索引編號從零開始。 也就是說,字串中的第一個字元位於索引零,最後一個字元位於 Length - 1。
搜尋會 startIndex
從字元位置開始,並往後繼續,直到 value
找到或 count
已檢查字元位置為止。 例如,如果 startIndex
為 Length - 1,則方法會搜尋字串中最後一個字元的回溯 count
字元。
參數 comparisonType
會指定使用下列專案來搜尋 value
參數:
- 目前或不可變的文化特性。
- 區分大小寫或不區分大小寫的搜尋。
- Word或序數比較規則。
給呼叫者的注意事項
字元集包含可忽略的字元,這些字元在執行語言或區分文化特性的比較時不列入考慮。 執行區分文化特性的搜尋 (也就是說,如果 comparisonType
不是 Ordinal 或 OrdinalIgnoreCase) 時,如果 value
包含可忽略的字元,則結果等於在已移除該字元的情況下搜尋。
在下列範例中 LastIndexOf(String, Int32, Int32, StringComparison) ,方法用來尋找兩個字串中最後 「m」 之前的第一個字元位置, (U+00AD) 後面接著 「m」 的最後一個字元位置。 只有其中一個字串包含必要的子字串。 如果範例在 .NET Framework 4 或更新版本上執行,在這兩種情況下,因為虛連字號是可忽略的字元,則此方法會在字串中執行區分文化特性的比較時傳回 「m」 的索引。 不過,當它執行序數比較時,它只會在第一個字串中找到子字串。 請注意,在第一個字串的案例中,其中包含虛連字號後面接著 「m」,此方法會在執行區分文化特性的比較時傳回 「m」 的索引。 只有在執行序數比較時,方法才會傳回第一個字串中選擇性連字號的索引。
string searchString = "\u00ADm";
string s1 = "ani\u00ADmal";
string s2 = "animal";
int position;
position = s1.LastIndexOf('m');
if (position >= 1)
{
Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture));
Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.Ordinal));
}
position = s2.LastIndexOf('m');
if (position >= 1)
{
Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture));
Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.Ordinal));
}
// The example displays the following output:
//
// 4
// 3
// 3
// -1
let searchString = "\u00ADm"
let s1 = "ani\u00ADmal"
let s2 = "animal"
let position = s1.LastIndexOf 'm'
if position >= 1 then
printfn $"{s1.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture)}"
printfn $"{s1.LastIndexOf(searchString, position, position, StringComparison.Ordinal)}"
let position = s2.LastIndexOf 'm'
if position >= 1 then
printfn $"{s2.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture)}"
printfn $"{s2.LastIndexOf(searchString, position, position, StringComparison.Ordinal)}"
// The example displays the following output:
//
// 4
// 3
// 3
// -1
Dim searchString As String = ChrW(&HAD) + "m"
Dim s1 As String = "ani" + ChrW(&HAD) + "m"
Dim s2 As String = "animal"
Dim position As Integer
position = s1.LastIndexOf("m"c)
If position >= 1 Then
Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture))
Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.Ordinal))
End If
position = s2.LastIndexOf("m"c)
If position >= 1 Then
Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture))
Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.Ordinal))
End If
' The example displays the following output:
'
' 4
' 3
' 3
' -1
適用於
LastIndexOf(String, Int32, StringComparison)
報告目前 String 物件中指定之字串最後一次出現時的所在索引 (以零為起始)。 搜尋會從指定的字元位置開始,然後反向朝字串的開頭進行。 參數會指定搜尋指定字串時要執行的比較類型。
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
其中一個列舉值,指定搜尋規則。
傳回
如果找到該字串,則為 value
參數以零為起始的索引位置,如果找不到該字串或者目前的執行個體等於 Empty,則為 -1。
例外狀況
value
為 null
。
comparisonType
不是有效的 StringComparison 值。
範例
下列範例示範方法的 LastIndexOf 三個多載,這些多載會使用列舉的不同值 StringComparison ,尋找另一個字串內最後一個出現的字串。
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
using System;
using System.Threading;
using System.Globalization;
class Sample
{
public static void Main()
{
string intro = "Find the last occurrence of a character using different " +
"values of StringComparison.";
string resultFmt = "Comparison: {0,-28} Location: {1,3}";
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
string CapitalAWithRing = "\u00c5";
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
string cat = "A Cheshire c" + "\u0061\u030a" + "t";
int loc = 0;
StringComparison[] scValues = {
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
StringComparison.OrdinalIgnoreCase };
// Clear the screen and display an introduction.
Console.Clear();
Console.WriteLine(intro);
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("The current culture is \"{0}\" - {1}.",
Thread.CurrentThread.CurrentCulture.Name,
Thread.CurrentThread.CurrentCulture.DisplayName);
// Display the string to search for and the string to search.
Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"",
CapitalAWithRing, cat);
Console.WriteLine();
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
Console.WriteLine("Part 1: Start index and count are specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion. Specify the
// start index.
Console.WriteLine("\nPart 2: Start index is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, sc);
Console.WriteLine(resultFmt, sc, loc);
}
}
}
/*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*/
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
open System
open System.Threading
open System.Globalization
let intro = "Find the last occurrence of a character using different values of StringComparison."
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let CapitalAWithRing = "\u00c5"
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues =
[| StringComparison.CurrentCulture
StringComparison.CurrentCultureIgnoreCase
StringComparison.InvariantCulture
StringComparison.InvariantCultureIgnoreCase
StringComparison.Ordinal
StringComparison.OrdinalIgnoreCase |]
// Clear the screen and display an introduction.
Console.Clear()
printfn $"{intro}"
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."
// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
printfn "Part 1: Start index and count are specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*)
' This code example demonstrates the
' System.String.LastIndexOf(String, ..., StringComparison) methods.
Imports System.Threading
Imports System.Globalization
Class Sample
Public Shared Sub Main()
Dim intro As String = "Find the last occurrence of a character using different " & _
"values of StringComparison."
Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
' Define a string to search for.
' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
Dim CapitalAWithRing As String = "Å"
' Define a string to search.
' The result of combining the characters LATIN SMALL LETTER A and COMBINING
' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
Dim cat As String = "A Cheshire c" & "å" & "t"
Dim loc As Integer = 0
Dim scValues As StringComparison() = { _
StringComparison.CurrentCulture, _
StringComparison.CurrentCultureIgnoreCase, _
StringComparison.InvariantCulture, _
StringComparison.InvariantCultureIgnoreCase, _
StringComparison.Ordinal, _
StringComparison.OrdinalIgnoreCase }
Dim sc As StringComparison
' Clear the screen and display an introduction.
Console.Clear()
Console.WriteLine(intro)
' Display the current culture because culture affects the result. For example,
' try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
Console.WriteLine("The current culture is ""{0}"" - {1}.", _
Thread.CurrentThread.CurrentCulture.Name, _
Thread.CurrentThread.CurrentCulture.DisplayName)
' Display the string to search for and the string to search.
Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
CapitalAWithRing, cat)
Console.WriteLine()
' Note that in each of the following searches, we look for
' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
' the string was not found.
' Search using different values of StringComparsion. Specify the start
' index and count.
Console.WriteLine("Part 1: Start index and count are specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion. Specify the
' start index.
Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion.
Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
End Sub
End Class
'
'Note: This code example was executed on a console whose user interface
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the last occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
備註
索引編號從零開始。 也就是說,字串中的第一個字元位於索引零,最後一個字元位於 Length - 1。
搜尋會從 startIndex
字元位置開始,並往後繼續,直到 value
找到或檢查第一個字元位置為止。 例如,如果 startIndex
為 Length - 1,則方法會搜尋字串中最後一個字元到開頭的每個字元。
參數 comparisonType
會指定使用目前或不可變文化特性、使用區分大小寫或不區分大小寫的搜尋,以及使用字組或序數比較規則來搜尋 value
參數。
給呼叫者的注意事項
字元集包含可忽略的字元,這些字元在執行語言或區分文化特性的比較時不列入考慮。 執行區分文化特性的搜尋 (也就是說,如果 comparisonType
不是 Ordinal 或 OrdinalIgnoreCase) 時,如果 value
包含可忽略的字元,則結果等於在已移除該字元的情況下搜尋。
在下列範例中 LastIndexOf(String, Int32, StringComparison) ,方法是用來尋找兩個字串中最後一個 「m」 的虛連字號位置 (U+00AD) 後面接著 「m」。 只有其中一個字串包含必要的子字串。 如果範例在 .NET Framework 4 或更新版本上執行,在這兩種情況下,因為虛連字號是可忽略的字元,則此方法會在字串中執行區分文化特性的比較時傳回 「m」 的索引。 請注意,在第一個字串的案例中,其中包含虛連字號後面接著 「m」,此方法會傳回 「m」 的索引,而不是虛連字號的索引。 只有在執行序數比較時,方法才會傳回第一個字串中選擇性連字號的索引。
string searchString = "\u00ADm";
string s1 = "ani\u00ADmal";
string s2 = "animal";
int position;
position = s1.LastIndexOf('m');
if (position >= 0)
{
Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.CurrentCulture));
Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.Ordinal));
}
position = s2.LastIndexOf('m');
if (position >= 0)
{
Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.CurrentCulture));
Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.Ordinal));
}
// The example displays the following output:
//
// 4
// 3
// 3
// -1
let searchString = "\u00ADm"
let s1 = "ani\u00ADmal"
let s2 = "animal"
let position = s1.LastIndexOf 'm'
if position >= 0 then
printfn $"{s1.LastIndexOf(searchString, position, StringComparison.CurrentCulture)}"
printfn $"{s1.LastIndexOf(searchString, position, StringComparison.Ordinal)}"
let position = s2.LastIndexOf 'm'
if position >= 0 then
printfn $"{s2.LastIndexOf(searchString, position, StringComparison.CurrentCulture)}"
printfn $"{s2.LastIndexOf(searchString, position, StringComparison.Ordinal)}"
// The example displays the following output:
//
// 4
// 3
// 3
// -1
Dim searchString As String = ChrW(&HAD) + "m"
Dim s1 As String = "ani" + ChrW(&HAD) + "mal"
Dim s2 As String = "animal"
Dim position As Integer
position = s1.LastIndexOf("m"c)
If position >= 0 Then
Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.CurrentCulture))
Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.Ordinal))
End If
position = s2.LastIndexOf("m"c)
If position >= 0 Then
Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.CurrentCulture))
Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.Ordinal))
End If
' The example displays the following output:
'
' 4
' 3
' 3
' -1
適用於
LastIndexOf(String, Int32, Int32)
回報這個執行個體中指定之字串最後一次出現時的所在索引 (以零為起始)。 搜尋會從指定的字元位置開始,然後反向朝字串開頭指定數目的字元位置進行。
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
的以零為起始索引位置,如果找不到該字串或者目前的執行個體等於 Empty,則為 -1。
例外狀況
value
為 null
。
count
為負。
-或-
目前的執行個體不等於 Empty,且 startIndex
為負。
-或-
目前的執行個體不等於 Empty,且 startIndex
大於這個執行個體的長度。
-或-
目前的執行個體不等於 Empty,且 startIndex
- count
+ 1 指定的位置不在此執行個體之內。
-或-
目前的執行個體等於 Empty,且 start
小於 -1 或大於零。
-或-
目前的執行個體等於 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
'
'
備註
索引編號從零開始。 也就是說,字串中的第一個字元位於索引零,最後一個字元位於 Length - 1。
搜尋會 startIndex
從這個實例的字元位置開始,並往後往回移至開始,直到 value
找到或 count
已檢查字元位置為止。 例如,如果 startIndex
為 Length - 1,則方法會搜尋字串中最後一個字元的回溯 count
字元。
這個方法會使用目前文化特性來執行單字 (區分大小寫和區分文化特性) 搜尋。
字元集包含可忽略的字元,這些字元在執行語言或區分文化特性的比較時不列入考慮。 執行區分文化特性的搜尋時,如果 value
包含可忽略的字元,則結果等於在已移除該字元的情況下搜尋。
在下列範例中 LastIndexOf ,方法是用來尋找兩個字串中的 「m」 或 「n」 (U+00AD 的軟連字號位置) 後面接著 「m」 或 「n」。 只有其中一個字串包含選擇性連字號。 在包含虛連字號後面接著 「m」 的字串案例中,搜尋後接 「m」 的虛連字號時, LastIndexOf
會傳回 「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
給呼叫者的注意事項
如 使用字串的最佳做法中所述,建議您避免呼叫取代預設值的字串比較方法,而是呼叫需要明確指定參數的方法。 若要使用目前文化特性的比較規則來執行這項作業,請藉由呼叫 LastIndexOf(String, Int32, Int32, StringComparison) 方法多載為其 參數的值 CurrentCulturecomparisonType
明確發出訊號。
另請參閱
適用於
LastIndexOf(Char, Int32, Int32)
報告這個執行個體的子字串中,指定的 Unicode 字元最後一次出現時的所在索引 (以零為起始)。 搜尋會從指定的字元位置開始,然後反向朝字串開頭指定數目的字元位置進行。
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
的以零為起始索引位置,如果找不到該字元或者目前的執行個體等於 Empty,則為 -1。
例外狀況
目前的執行個體不等於 Empty,且 startIndex
小於零,或者大於或等於這個執行個體的長度。
-或-
目前的執行個體不等於 Empty,且 startIndex
- count
+ 1 小於零。
範例
下列範例會尋找子字串中所有出現字元的索引,從子字串的結尾到子字串的開頭。
// 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
'
'
備註
索引編號從零開始。 也就是說,字串中的第一個字元位於索引零,最後一個字元位於 Length - 1。
這個方法會開始搜尋 startIndex
字元位置,並往後往回移至這個實例的開頭,直到 value
找到或 count
已檢查字元位置為止。 例如,如果 startIndex
為 Length - 1,則方法會搜尋字串中最後一個字元的回溯 count
字元。 搜尋會區分大小寫。
這個方法會執行不區分文化特性的序數 (不區分文化特性) 搜尋,其中字元只有在 Unicode 純量值相同時才視為另一個字元。 若要執行區分文化特性的搜尋,請使用 CompareInfo.LastIndexOf 方法,其中代表預先編譯字元的 Unicode 純量值,例如 ligature 「Æ」 (U+00C6) ,可能會視為相當於正確序列中任何出現的字元元件,例如 「AE」 (U+0041、U+0045) ,視文化特性而定。
另請參閱
適用於
LastIndexOf(String, Int32)
回報這個執行個體中指定之字串最後一次出現時的所在索引 (以零為起始)。 搜尋會從指定的字元位置開始,然後反向朝字串的開頭進行。
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
的以零為起始索引位置,如果找不到該字串或者目前的執行個體等於 Empty,則為 -1。
例外狀況
value
為 null
。
範例
下列範例會尋找目標字串中所有出現的字串索引,從目標字串的結尾到目標字串的開頭。
// 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
'
'
備註
索引編號從零開始。 也就是說,字串中的第一個字元位於索引零,最後一個字元位於 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
參數的值 CurrentCulture 呼叫 方法多載,以 LastIndexOf(String, Int32, StringComparison) 明確表示您的意圖。
另請參閱
適用於
LastIndexOf(Char, Int32)
報告這個執行個體中指定之 Unicode 字元最後一次出現時的所在索引 (以零為起始)。 搜尋會從指定的字元位置開始,然後反向朝字串的開頭進行。
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
的以零為起始索引位置,如果找不到該字元或者目前的執行個體等於 Empty,則為 -1。
例外狀況
目前的執行個體不等於 Empty,且 startIndex
小於零,或者大於或等於這個執行個體的長度。
範例
下列範例會尋找字串中所有出現的字元索引,從字串結尾到字串的開頭。
// 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
'
備註
索引編號從零開始。 也就是說,字串中的第一個字元位於索引零,最後一個字元位於 Length - 1。 這個方法會開始搜尋 startIndex
這個實例的字元位置,並往後往回移至目前實例的開頭,直到 value
找到或檢查第一個字元位置為止。 例如,如果 startIndex
為 Length - 1,則方法會搜尋字串中最後一個字元到開頭的每個字元。 搜尋會區分大小寫。
這個方法會執行不區分文化特性的序數 (不區分文化特性) 搜尋,其中字元只有在 Unicode 純量值相同時,才會被視為相當於另一個字元。 若要執行區分文化特性的搜尋,請使用 CompareInfo.LastIndexOf 方法,其中代表預先編譯字元的 Unicode 純量值,例如 ligature 「Æ」 (U+00C6) ,可能會視為相當於正確序列中任何出現的字元元件,例如 「AE」 (U+0041、U+0045) ,視文化特性而定。
另請參閱
適用於
LastIndexOf(String)
回報這個執行個體中指定之字串最後一次出現時的所在索引 (以零為起始)。
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
以零為起始的起始索引位置,如未找到,則為 -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>
備註
索引編號從零開始。 也就是說,字串中的第一個字元位於索引零,最後一個字元位於 Length - 1。
搜尋會從這個實例的最後一個字元位置開始,並往後往回移至開始,直到 value
找到或檢查第一個字元位置為止。
這個方法會使用目前文化特性來執行單字 (區分大小寫和區分文化特性) 搜尋。
字元集包含可忽略的字元,這些字元在執行語言或區分文化特性的比較時不列入考慮。 執行區分文化特性的搜尋時,如果 value
包含可忽略的字元,則結果等於在已移除該字元的情況下搜尋。
在下列範例中 LastIndexOf(String) ,方法是用來尋找兩個子字串 (一個虛連字號,後面接著 「n」 和兩個字串中的 「m」) 。 只有其中一個字串包含選擇性連字號。 如果範例在 .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 呼叫 方法多載,以明確 LastIndexOf(String, StringComparison) 表示您的意圖。
另請參閱
適用於
LastIndexOf(Char)
報告這個執行個體中指定之 Unicode 字元最後一次出現時的所在索引 (以零為起始)。
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
以零為起始的索引位置,如果找不到為 -1。
範例
下列範例會 ExtractFilename
定義方法,該方法會使用 LastIndexOf(Char) 方法來尋找字串中的最後一個目錄分隔符號,以及擷取字串的檔案名。 如果檔案存在,此方法會傳回檔案名,而不傳回其路徑。
using System;
using System.IO;
public class TestLastIndexOf
{
public static void Main()
{
string filename;
filename = ExtractFilename(@"C:\temp\");
Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
filename = ExtractFilename(@"C:\temp\delegate.txt");
Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
filename = ExtractFilename("delegate.txt");
Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
filename = ExtractFilename(@"C:\temp\notafile.txt");
Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
}
public static string ExtractFilename(string filepath)
{
// If path ends with a "\", it's a path only so return String.Empty.
if (filepath.Trim().EndsWith(@"\"))
return String.Empty;
// Determine where last backslash is.
int position = filepath.LastIndexOf('\\');
// If there is no backslash, assume that this is a filename.
if (position == -1)
{
// Determine whether file exists in the current directory.
if (File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath))
return filepath;
else
return String.Empty;
}
else
{
// Determine whether file exists using filepath.
if (File.Exists(filepath))
// Return filename without file path.
return filepath.Substring(position + 1);
else
return String.Empty;
}
}
}
open System
open System.IO
let extractFilename (filepath: string) =
// If path ends with a "\", it's a path only so return String.Empty.
if filepath.Trim().EndsWith @"\" then
String.Empty
else
// Determine where last backslash is.
let position = filepath.LastIndexOf '\\'
// If there is no backslash, assume that this is a filename.
if position = -1 then
// Determine whether file exists in the current directory.
if File.Exists(Environment.CurrentDirectory + string Path.DirectorySeparatorChar + filepath) then
filepath
else
String.Empty
else
// Determine whether file exists using filepath.
if File.Exists filepath then
// Return filename without file path.
filepath.Substring(position + 1)
else
String.Empty
do
let filename = extractFilename @"C:\temp\"
printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""
let filename = extractFilename @"C:\temp\delegate.txt"
printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""
let filename = extractFilename "delegate.txt"
printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""
let filename = extractFilename @"C:\temp\notafile.txt"
printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""
Imports System.IO
Public Module Test
Public Sub Main()
Dim filename As String
filename = ExtractFilename("C:\temp\")
Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
filename = ExtractFilename("C:\temp\delegate.txt")
Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
filename = ExtractFilename("delegate.txt")
Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
filename = ExtractFilename("C:\temp\notafile.txt")
Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
End Sub
Public Function ExtractFilename(filepath As String) As String
' If path ends with a "\", it's a path only so return String.Empty.
If filepath.Trim().EndsWith("\") Then Return String.Empty
' Determine where last backslash is.
Dim position As Integer = filepath.LastIndexOf("\"c)
' If there is no backslash, assume that this is a filename.
If position = -1 Then
' Determine whether file exists in the current directory.
If File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath) Then
Return filepath
Else
Return String.Empty
End If
Else
' Determine whether file exists using filepath.
If File.Exists(filepath) Then
' Return filename without file path.
Return filepath.Substring(position + 1)
Else
Return String.Empty
End If
End If
End Function
End Module
' The example displays the following output:
' delegate.txt
備註
索引編號從零開始。 也就是說,字串中的第一個字元位於索引零,最後一個字元位於 Length - 1。
這個方法會開始搜尋這個實例的最後一個字元位置,並往後往回移至開始,直到 value
找到或檢查第一個字元位置為止。 搜尋會區分大小寫。
這個方法會執行不區分文化特性的序數 (不區分文化特性) 搜尋,其中字元只有在 Unicode 純量值相同時,才會被視為相當於另一個字元。 若要執行區分文化特性的搜尋,請使用 CompareInfo.LastIndexOf 方法,其中代表預先編譯字元的 Unicode 純量值,例如 ligature 「Æ」 (U+00C6) ,可能會視為相當於正確序列中任何出現的字元元件,例如 「AE」 (U+0041、U+0045) ,視文化特性而定。
另請參閱
適用於
LastIndexOf(String, StringComparison)
報告目前 String 物件中指定之字串最後一次出現時的所在索引 (以零為起始)。 參數會指定要用於指定字串的搜尋類型。
public:
int LastIndexOf(System::String ^ value, StringComparison comparisonType);
public int LastIndexOf (string value, StringComparison comparisonType);
member this.LastIndexOf : string * StringComparison -> int
Public Function LastIndexOf (value As String, comparisonType As StringComparison) As Integer
參數
- value
- String
要搜尋的字串。
- comparisonType
- StringComparison
其中一個列舉值,指定搜尋規則。
傳回
如果找到該字串,則為 value
參數的以零為起始的起始索引位置,否則為 -1。
例外狀況
value
為 null
。
comparisonType
不是有效的 StringComparison 值。
範例
下列範例示範方法的 LastIndexOf 三個多載,這些多載會使用列舉的不同值 StringComparison ,尋找另一個字串內最後一個出現的字串。
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
using System;
using System.Threading;
using System.Globalization;
class Sample
{
public static void Main()
{
string intro = "Find the last occurrence of a character using different " +
"values of StringComparison.";
string resultFmt = "Comparison: {0,-28} Location: {1,3}";
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
string CapitalAWithRing = "\u00c5";
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
string cat = "A Cheshire c" + "\u0061\u030a" + "t";
int loc = 0;
StringComparison[] scValues = {
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
StringComparison.OrdinalIgnoreCase };
// Clear the screen and display an introduction.
Console.Clear();
Console.WriteLine(intro);
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("The current culture is \"{0}\" - {1}.",
Thread.CurrentThread.CurrentCulture.Name,
Thread.CurrentThread.CurrentCulture.DisplayName);
// Display the string to search for and the string to search.
Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"",
CapitalAWithRing, cat);
Console.WriteLine();
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
Console.WriteLine("Part 1: Start index and count are specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion. Specify the
// start index.
Console.WriteLine("\nPart 2: Start index is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, sc);
Console.WriteLine(resultFmt, sc, loc);
}
}
}
/*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*/
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
open System
open System.Threading
open System.Globalization
let intro = "Find the last occurrence of a character using different values of StringComparison."
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let CapitalAWithRing = "\u00c5"
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues =
[| StringComparison.CurrentCulture
StringComparison.CurrentCultureIgnoreCase
StringComparison.InvariantCulture
StringComparison.InvariantCultureIgnoreCase
StringComparison.Ordinal
StringComparison.OrdinalIgnoreCase |]
// Clear the screen and display an introduction.
Console.Clear()
printfn $"{intro}"
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."
// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
printfn "Part 1: Start index and count are specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*)
' This code example demonstrates the
' System.String.LastIndexOf(String, ..., StringComparison) methods.
Imports System.Threading
Imports System.Globalization
Class Sample
Public Shared Sub Main()
Dim intro As String = "Find the last occurrence of a character using different " & _
"values of StringComparison."
Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
' Define a string to search for.
' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
Dim CapitalAWithRing As String = "Å"
' Define a string to search.
' The result of combining the characters LATIN SMALL LETTER A and COMBINING
' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
Dim cat As String = "A Cheshire c" & "å" & "t"
Dim loc As Integer = 0
Dim scValues As StringComparison() = { _
StringComparison.CurrentCulture, _
StringComparison.CurrentCultureIgnoreCase, _
StringComparison.InvariantCulture, _
StringComparison.InvariantCultureIgnoreCase, _
StringComparison.Ordinal, _
StringComparison.OrdinalIgnoreCase }
Dim sc As StringComparison
' Clear the screen and display an introduction.
Console.Clear()
Console.WriteLine(intro)
' Display the current culture because culture affects the result. For example,
' try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
Console.WriteLine("The current culture is ""{0}"" - {1}.", _
Thread.CurrentThread.CurrentCulture.Name, _
Thread.CurrentThread.CurrentCulture.DisplayName)
' Display the string to search for and the string to search.
Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
CapitalAWithRing, cat)
Console.WriteLine()
' Note that in each of the following searches, we look for
' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
' the string was not found.
' Search using different values of StringComparsion. Specify the start
' index and count.
Console.WriteLine("Part 1: Start index and count are specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion. Specify the
' start index.
Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion.
Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
End Sub
End Class
'
'Note: This code example was executed on a console whose user interface
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the last occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
備註
索引編號從零開始。 也就是說,字串中的第一個字元位於索引零,最後一個字元位於 Length - 1。
參數 comparisonType
會指定使用下列專案來搜尋 value
參數:
- 目前或不可變的文化特性。
- 區分大小寫或不區分大小寫的搜尋。
- Word或序數比較規則。
搜尋會從這個實例的最後一個字元位置開始,並往後往回移至開始,直到 value
找到或檢查第一個字元位置為止。
給呼叫者的注意事項
字元集包含可忽略的字元,這些字元在執行語言或區分文化特性的比較時不列入考慮。 執行區分文化特性的搜尋 (也就是說,如果 options
不是 Ordinal 或 OrdinalIgnoreCase) 時,如果 value
包含可忽略的字元,則結果等於在已移除該字元的情況下搜尋。
在下列範例中 LastIndexOf(String, StringComparison) ,方法是用來尋找兩個子字串, (一個虛連字號後面接著 「n」,以及兩個字串中後面接著 「m」) 的虛連字號。 只有其中一個字串包含選擇性連字號。 如果範例是在 .NET Framework 4 或更新版本上執行,因為虛連字號是可忽略的字元,區分文化特性的搜尋會傳回相同的值,如果搜尋字串中未包含虛連字號,則會傳回該值。 不過,序數搜尋會在一個字串中成功尋找虛連字號,並報告它不存在於第二個字串中。
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