String.LastIndexOf 方法

定义

报告指定 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。

例外

valuenull

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
'

注解

索引编号从零开始。 也就是说,字符串中的第一个字符位于索引 0 处,最后一个字符位于 Length - 1。

搜索从字符位置开始 startIndex ,然后向后继续,直到 value 找到字符位置或 count 检查字符位置。 例如,如果 startIndexLength - 1,则 方法从字符串中的最后一个字符中搜索向后 count 字符。

参数 comparisonType 指定使用以下项搜索 value 参数:

  • 当前区域性或固定区域性。
  • 区分大小写或不区分大小写的搜索。
  • Word或序号比较规则。

调用方说明

字符集包括可忽略字符,在执行语言性的或区分区域性的比较时该字符不被考虑。 在区分区域性的搜索 (即,如果 comparisonType 不是 OrdinalOrdinalIgnoreCase) 中,如果 value 包含一个可忽略字符,则结果与移除了该字符的搜索等效。

在下面的示例中, LastIndexOf(String, Int32, Int32, StringComparison) 方法用于查找软连字符的位置, (U+00AD) 后跟“m”,但两个字符串中最后一个“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。

例外

valuenull

当前实例不等于 Empty,并且 startIndex 小于零或大于当前实例的长度。

当前实例等于 Empty,并且 startIndex 小于-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
'

注解

索引编号从零开始。 也就是说,字符串中的第一个字符位于索引 0 处,最后一个字符位于 Length - 1。

搜索从字符位置开始 startIndex ,然后向后继续,直到 value 找到或检查完第一个字符位置。 例如,如果 startIndexLength - 1,则方法从字符串中的最后一个字符到开头搜索每个字符。

参数 comparisonType 指定使用当前或固定区域性、使用区分大小写或不区分大小写的搜索以及使用单词或序号比较规则来搜索 value 参数。

调用方说明

字符集包括可忽略字符,在执行语言性的或区分区域性的比较时该字符不被考虑。 在区分区域性的搜索 (即,如果 comparisonType 不是 OrdinalOrdinalIgnoreCase) 中,如果 value 包含一个可忽略字符,则结果与移除了该字符的搜索等效。

在下面的示例中, LastIndexOf(String, Int32, StringComparison) 方法用于查找软连字符的位置 (U+00AD) 后跟一个“m”,从两个字符串中的最后一个“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。

例外

valuenull

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

注解

索引编号从零开始。 也就是说,字符串中的第一个字符位于索引 0 处,最后一个字符位于 Length - 1。

搜索从此实例的 startIndex 字符位置开始,然后向后向开始,直到 value 找到或 count 检查字符位置。 例如,如果 startIndexLength - 1,则 方法从字符串中的最后一个字符中搜索向后 count 字符。

此方法使用当前区域性执行单词 (区分大小写和区分区域性) 搜索。

字符集包括可忽略字符,在执行语言性的或区分区域性的比较时该字符不被考虑。 在区分区域性的搜索中,如果 value 包含一个可忽略字符,则结果与移除了该字符的搜索等效。

在下面的示例中, LastIndexOf 方法用于查找软连字符的位置 (U+00AD) 后跟两个字符串中的“m”或“n”。 只有一个字符串包含软连字符。 对于包含后跟“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

调用方说明

使用字符串的最佳做法中所述,建议避免调用替换默认值的字符串比较方法,而是调用需要显式指定参数的方法。 若要使用当前区域性的比较规则执行此操作,请通过调用LastIndexOf(String, Int32, Int32, StringComparison)方法重载(其comparisonType参数的 CurrentCulture 值为 )来显式发出意图信号。 如果不需要语言感知比较,请考虑使用 Ordinal

另请参阅

适用于

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

注解

索引编号从零开始。 也就是说,字符串中的第一个字符位于索引 0 处,最后一个字符位于 Length - 1。

此方法从字符位置开始搜索 startIndex ,然后向后向此实例的开头,直到 value 找到或 count 检查字符位置。 例如,如果 startIndexLength - 1,则 方法从字符串中的最后一个字符中搜索向后 count 字符。 搜索区分大小写。

此方法执行序号 (不区分区域性) 搜索,其中仅当字符的 Unicode 标量值相同时,才认为该字符等效于另一个字符。 若要执行区分区域性的搜索,请使用 CompareInfo.LastIndexOf 方法,其中表示预分解字符的 Unicode 标量值(如连字“Æ” (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。

例外

valuenull

当前实例不等于 Empty,并且 startIndex 小于零或大于当前实例的长度。

当前实例等于 Empty,并且 startIndex 小于-1 或大于零。

示例

下面的示例查找目标字符串中字符串的所有匹配项的索引,从目标字符串的末尾到目标字符串的开头。

// 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 处,最后一个字符位于 Length - 1。

搜索从此实例的 startIndex 字符位置开始,然后向后向开始,直到 value 找到或检查完第一个字符位置。 例如,如果 startIndexLength - 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

调用方说明

使用字符串的最佳做法中所述,建议避免调用替换默认值的字符串比较方法,而是调用需要显式指定参数的方法。 若要通过使用当前区域性的比较规则查找位于特定字符位置之前的子字符串的索引,请通过调用LastIndexOf(String, Int32, StringComparison)方法重载(其comparisonType参数的 CurrentCulture 值为 )来明确表示你的意图。 如果不需要语言感知比较,请考虑使用 Ordinal

另请参阅

适用于

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
'

注解

索引编号从零开始。 也就是说,字符串中的第一个字符位于索引 0 处,最后一个字符位于 Length - 1。 此方法开始搜索此实例的 startIndex 字符位置,然后向后向当前实例的开头,直到 value 找到或检查完第一个字符位置。 例如,如果 startIndexLength - 1,则方法从字符串中的最后一个字符到开头搜索每个字符。 搜索区分大小写。

此方法执行不区分区域性的序号 () 搜索,其中仅当一个字符的 Unicode 标量值相同时,才认为该字符等效于另一个字符。 若要执行区分区域性的搜索,请使用 CompareInfo.LastIndexOf 方法,其中表示预分解字符的 Unicode 标量值(如连字“Æ” (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。

例外

valuenull

示例

以下示例从字符串中删除开始和结束 HTML 标记(如果标记以字符串开头和结尾)。 如果字符串以右方括号字符 (“”>) 结尾,则示例使用 LastIndexOf 方法查找结束标记的开头。

using System;

public class Example 
{
   public static void Main() 
   {
      string[] strSource = { "<b>This is bold text</b>", "<H1>This is large Text</H1>",
               "<b><i><font color=green>This has multiple tags</font></i></b>",
               "<b>This has <i>embedded</i> tags.</b>",
               "This line ends with a greater than symbol and should not be modified>" };

      // Strip HTML start and end tags from each string if they are present.
      foreach (string s in strSource)
      {
         Console.WriteLine("Before: " + s);
         string item = s;
         // Use EndsWith to find a tag at the end of the line.
         if (item.Trim().EndsWith(">")) 
         {
            // Locate the opening tag.
            int endTagStartPosition = item.LastIndexOf("</");
            // Remove the identified section, if it is valid.
            if (endTagStartPosition >= 0 )
               item = item.Substring(0, endTagStartPosition);

            // Use StartsWith to find the opening tag.
            if (item.Trim().StartsWith("<"))
            {
               // Locate the end of opening tab.
               int openTagEndPosition = item.IndexOf(">");
               // Remove the identified section, if it is valid.
               if (openTagEndPosition >= 0)
                  item = item.Substring(openTagEndPosition + 1);
            }      
         }
         // Display the trimmed string.
         Console.WriteLine("After: " + item);
         Console.WriteLine();
      }                   
   }
}
// The example displays the following output:
//    Before: <b>This is bold text</b>
//    After: This is bold text
//    
//    Before: <H1>This is large Text</H1>
//    After: This is large Text
//    
//    Before: <b><i><font color=green>This has multiple tags</font></i></b>
//    After: <i><font color=green>This has multiple tags</font></i>
//    
//    Before: <b>This has <i>embedded</i> tags.</b>
//    After: This has <i>embedded</i> tags.
//    
//    Before: This line ends with a greater than symbol and should not be modified>
//    After: This line ends with a greater than symbol and should not be modified>
let strSource = 
    [| "<b>This is bold text</b>"; "<H1>This is large Text</H1>"
       "<b><i><font color=green>This has multiple tags</font></i></b>"
       "<b>This has <i>embedded</i> tags.</b>"
       "This line ends with a greater than symbol and should not be modified>" |]

// Strip HTML start and end tags from each string if they are present.
for s in strSource do
    printfn $"Before: {s}"
    let mutable item = s
    // Use EndsWith to find a tag at the end of the line.
    if item.Trim().EndsWith ">" then
        // Locate the opening tag.
        let endTagStartPosition = item.LastIndexOf "</"
        // Remove the identified section, if it is valid.
        if endTagStartPosition >= 0 then
            item <- item.Substring(0, endTagStartPosition)

        // Use StartsWith to find the opening tag.
        if item.Trim().StartsWith "<" then
            // Locate the end of opening tab.
            let openTagEndPosition = item.IndexOf ">"
            // Remove the identified section, if it is valid.
            if openTagEndPosition >= 0 then
                item <- item.Substring(openTagEndPosition + 1)
    // Display the trimmed string.
    printfn "After: {item}"
    printfn ""
// The example displays the following output:
//    Before: <b>This is bold text</b>
//    After: This is bold text
//
//    Before: <H1>This is large Text</H1>
//    After: This is large Text
//
//    Before: <b><i><font color=green>This has multiple tags</font></i></b>
//    After: <i><font color=green>This has multiple tags</font></i>
//
//    Before: <b>This has <i>embedded</i> tags.</b>
//    After: This has <i>embedded</i> tags.
//
//    Before: This line ends with a greater than symbol and should not be modified>
//    After: This line ends with a greater than symbol and should not be modified>
Module Example
   Public Sub Main()
      Dim strSource As String() = { "<b>This is bold text</b>", _
                    "<H1>This is large Text</H1>", _
                    "<b><i><font color=green>This has multiple tags</font></i></b>", _
                    "<b>This has <i>embedded</i> tags.</b>", _
                    "This line ends with a greater than symbol and should not be modified>" }

      ' Strip HTML start and end tags from each string if they are present.
      For Each s As String In strSource
         Console.WriteLine("Before: " + s)
         ' Use EndsWith to find a tag at the end of the line.
         If s.Trim().EndsWith(">") Then 
            ' Locate the opening tag.
            Dim endTagStartPosition As Integer = s.LastIndexOf("</")
            ' Remove the identified section if it is valid.
            If endTagStartPosition >= 0 Then
               s = s.Substring(0, endTagStartPosition)
            End If
            
            ' Use StartsWith to find the opening tag.
            If s.Trim().StartsWith("<") Then
               ' Locate the end of opening tab.
               Dim openTagEndPosition As Integer = s.IndexOf(">")
               ' Remove the identified section if it is valid.
               If openTagEndPosition >= 0 Then
                  s = s.Substring(openTagEndPosition + 1)
               End If   
            End If      
         End If
         ' Display the trimmed string.
         Console.WriteLine("After: " + s)
         Console.WriteLine()
      Next                   
   End Sub
End Module
' The example displays the following output:
'    Before: <b>This is bold text</b>
'    After: This is bold text
'    
'    Before: <H1>This is large Text</H1>
'    After: This is large Text
'    
'    Before: <b><i><font color=green>This has multiple tags</font></i></b>
'    After: <i><font color=green>This has multiple tags</font></i>
'    
'    Before: <b>This has <i>embedded</i> tags.</b>
'    After: This has <i>embedded</i> tags.
'    
'    Before: This line ends with a greater than symbol and should not be modified>
'    After: This line ends with a greater than symbol and should not be modified>

注解

索引编号从零开始。 也就是说,字符串中的第一个字符位于索引零,最后一个字符位于 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

调用方说明

使用字符串的最佳做法中所述,建议避免调用替换默认值的字符串比较方法,而是调用需要显式指定参数的方法。 若要使用当前区域性的比较规则在字符串实例中查找子字符串的最后一个索引,请通过调用LastIndexOf(String, StringComparison)方法重载(其comparisonType参数的 值为 CurrentCulture )来明确表示你的意图。 如果不需要语言感知比较,请考虑使用 Ordinal

另请参阅

适用于

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 标量值(如连字“Æ” (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。

例外

valuenull

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 不是 OrdinalOrdinalIgnoreCase) 中,如果 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

适用于