String.LastIndexOf Metódus

Definíció

Egy megadott Unicode-karakter vagy sztring utolsó előfordulásának nullaalapú indexpozícióját jelenti ebben a példányban. A metódus -1 ad vissza, ha a karakter vagy a sztring nem található ebben a példányban.

Túlterhelések

Name Description
LastIndexOf(String, Int32, Int32, StringComparison)

Egy adott sztring utolsó előfordulásának nullaalapú indexpozícióját jelenti ebben a példányban. A keresés egy megadott karakterhelyzetben kezdődik, és a sztring elejére halad a megadott számú karakterpozíció esetében. A paraméter megadja a megadott sztring keresésekor végrehajtandó összehasonlítás típusát.

LastIndexOf(Char, Int32, Int32, StringComparison)
LastIndexOf(Rune, Int32, StringComparison)
LastIndexOf(Rune, Int32, Int32)
LastIndexOf(String, Int32, StringComparison)

Egy adott sztring utolsó előfordulásának nulla alapú indexét jelenti az aktuális String objektumon belül. A keresés egy megadott karakterhelyzetben kezdődik, és a sztring elejéhez visszafelé halad. A paraméter megadja a megadott sztring keresésekor végrehajtandó összehasonlítás típusát.

LastIndexOf(String, Int32, Int32)

Egy adott sztring utolsó előfordulásának nullaalapú indexpozícióját jelenti ebben a példányban. A keresés egy megadott karakterhelyzetben kezdődik, és a sztring elején halad előre meghatározott számú karakterpozíció esetén.

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

A megadott Unicode-karakter utolsó előfordulásának nullaalapú indexpozícióját jelenti a példányon belüli alsztringben. A keresés egy megadott karakterhelyzetben kezdődik, és a sztring elején halad előre meghatározott számú karakterpozíció esetén.

LastIndexOf(String, Int32)

Egy adott sztring utolsó előfordulásának nullaalapú indexpozícióját jelenti ebben a példányban. A keresés egy megadott karakterhelyzetben kezdődik, és a sztring elejéhez visszafelé halad.

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

Egy adott sztring utolsó előfordulásának nulla alapú indexét jelenti az aktuális String objektumon belül. A paraméter megadja a megadott sztringhez használandó keresés típusát.

LastIndexOf(Rune, Int32, Int32, StringComparison)
LastIndexOf(Char, StringComparison)
LastIndexOf(Char, Int32)

Egy megadott Unicode-karakter utolsó előfordulásának nullaalapú indexpozícióját jelenti ebben a példányban. A keresés egy megadott karakterhelyzetben kezdődik, és a sztring elejéhez visszafelé halad.

LastIndexOf(Rune)
LastIndexOf(String)

Egy adott sztring utolsó előfordulásának nullaalapú indexpozícióját jelenti ebben a példányban.

LastIndexOf(Char)

Egy megadott Unicode-karakter utolsó előfordulásának nullaalapú indexpozícióját jelenti ebben a példányban.

LastIndexOf(Rune, StringComparison)

LastIndexOf(String, Int32, Int32, StringComparison)

Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs

Egy adott sztring utolsó előfordulásának nullaalapú indexpozícióját jelenti ebben a példányban. A keresés egy megadott karakterhelyzetben kezdődik, és a sztring elejére halad a megadott számú karakterpozíció esetében. A paraméter megadja a megadott sztring keresésekor végrehajtandó összehasonlítás típusát.

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

Paraméterek

value
String

A keresendő sztring.

startIndex
Int32

A keresés kezdőpozíciója. A keresés a startIndex példány kezdetétől folytatódik.

count
Int32

A vizsgálandó karakterpozíciók száma.

comparisonType
StringComparison

A keresés szabályait meghatározó enumerálási értékek egyike.

Válaszok

A paraméter nulla alapú kezdő indexpozíciója, ha a sztring value található, vagy -1, ha nem található, vagy ha az aktuális példány egyenlő Empty.

Kivételek

value az null.

count negatív.

-vagy-

Az aktuális példány nem egyenlő Empty, és startIndex negatív.

-vagy-

Az aktuális példány nem egyenlő Empty, és startIndex nagyobb, mint a példány hossza.

-vagy-

Az aktuális példány nem egyenlő Empty, és startIndex + 1 – count olyan pozíciót ad meg, amely nem ezen a példányon belül található.

-vagy-

Az aktuális példány egyenlő Empty , és startIndex kisebb, mint -1 vagy nagyobb, mint nulla.

-vagy-

Az aktuális példány egyenlő Empty , és count nagyobb, mint 1.

comparisonType érvénytelen StringComparison érték.

Példák

Az alábbi példa a metódus három túlterhelését LastIndexOf mutatja be, amelyek az enumerálás különböző értékeit használva keresik meg egy sztring utolsó előfordulását egy StringComparison másik sztringben.

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

Megjegyzések

Az indexszámozás nulláról indul. Ez azt jelenti, hogy a sztring első karaktere nulla, az utolsó Length pedig - 1.

A keresés a startIndex karakterhelyzetben kezdődik, és visszafelé halad, amíg meg nem value találja count vagy meg nem vizsgálja a karakterpozíciókat. Ha például startIndexLength - 1, a metódus visszafelé count keres karaktereket a sztring utolsó karakteréből.

A comparisonType paraméter a következőkkel keresi meg a paramétert value :

  • A jelenlegi vagy invariáns kultúra.
  • Kis- és nagybetűk megkülönböztetése vagy érzéketlen keresés.
  • Word vagy a sorszámok összehasonlítására vonatkozó szabályokat.

Megjegyzések a hívókhoz

A karakterkészletek figyelmen kívül hagyható karaktereket tartalmaznak, amelyek nyelvi vagy kulturális szempontból érzékeny összehasonlítások során nem figyelembe vett karakterek. Ha egy kulturális szempontból érzékeny keresésben (vagyis ha comparisonType nem Ordinal , vagy OrdinalIgnoreCase), ha value figyelmen kívül hagyható karaktert tartalmaz, akkor az eredmény egyenértékű az eltávolított karakterrel végzett kereséssel.

A következő példában a LastIndexOf(String, Int32, Int32, StringComparison) módszer egy puha kötőjel (U+00AD) pozíciójának megkeresésére szolgál, majd egy "m" karaktert a két sztring utolsó "m" előtti első karakterpozíciója ki nem. Csak az egyik sztring tartalmazza a szükséges részszűrést. Ha a példa .NET Framework 4-en vagy újabb verzióján fut, mindkét esetben, mivel a helyreállítható kötőjel egy figyelmen kívül hagyható karakter, a metódus az "m" indexét adja vissza a sztringben, amikor kulturális szempontból érzékeny összehasonlítást végez. Ha azonban sorszám-összehasonlítást végez, csak az első sztringben találja meg az alsztringet. Vegye figyelembe, hogy az első sztring esetében, amely magában foglalja a helyreállítható kötőjelet, majd az "m"-t, a metódus az "m" indexét adja vissza, amikor kultúraérzékeny összehasonlítást végez. A metódus csak akkor adja vissza a helyreállítható kötőjel indexét az első sztringben, ha a függvénydinális összehasonlítást végez.

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

A következőre érvényes:

LastIndexOf(Char, Int32, Int32, StringComparison)

Forrás:
String.Searching.cs
public:
 int LastIndexOf(char value, int startIndex, int count, StringComparison comparisonType);
public int LastIndexOf(char value, int startIndex, int count, StringComparison comparisonType);
member this.LastIndexOf : char * int * int * StringComparison -> int
Public Function LastIndexOf (value As Char, startIndex As Integer, count As Integer, comparisonType As StringComparison) As Integer

Paraméterek

value
Char
startIndex
Int32
count
Int32
comparisonType
StringComparison

Válaszok

A következőre érvényes:

LastIndexOf(Rune, Int32, StringComparison)

Forrás:
String.Searching.cs
public:
 int LastIndexOf(System::Text::Rune value, int startIndex, StringComparison comparisonType);
public int LastIndexOf(System.Text.Rune value, int startIndex, StringComparison comparisonType);
member this.LastIndexOf : System.Text.Rune * int * StringComparison -> int
Public Function LastIndexOf (value As Rune, startIndex As Integer, comparisonType As StringComparison) As Integer

Paraméterek

value
Rune
startIndex
Int32
comparisonType
StringComparison

Válaszok

A következőre érvényes:

LastIndexOf(Rune, Int32, Int32)

Forrás:
String.Searching.cs
public:
 int LastIndexOf(System::Text::Rune value, int startIndex, int count);
public int LastIndexOf(System.Text.Rune value, int startIndex, int count);
member this.LastIndexOf : System.Text.Rune * int * int -> int
Public Function LastIndexOf (value As Rune, startIndex As Integer, count As Integer) As Integer

Paraméterek

value
Rune
startIndex
Int32
count
Int32

Válaszok

A következőre érvényes:

LastIndexOf(String, Int32, StringComparison)

Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs

Egy adott sztring utolsó előfordulásának nulla alapú indexét jelenti az aktuális String objektumon belül. A keresés egy megadott karakterhelyzetben kezdődik, és a sztring elejéhez visszafelé halad. A paraméter megadja a megadott sztring keresésekor végrehajtandó összehasonlítás típusát.

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

Paraméterek

value
String

A keresendő sztring.

startIndex
Int32

A keresés kezdőpozíciója. A keresés a startIndex példány kezdetétől folytatódik.

comparisonType
StringComparison

A keresés szabályait meghatározó enumerálási értékek egyike.

Válaszok

A paraméter nulla alapú kezdő indexpozíciója, ha a sztring value található, vagy -1, ha nem található, vagy ha az aktuális példány egyenlő Empty.

Kivételek

value az null.

Az aktuális példány nem egyenlő Empty, és startIndex kisebb, mint nulla vagy nagyobb, mint az aktuális példány hossza.

-vagy-

Az aktuális példány egyenlő Empty, és startIndex kisebb, mint -1 vagy nagyobb, mint nulla.

comparisonType érvénytelen StringComparison érték.

Példák

Az alábbi példa a metódus három túlterhelését LastIndexOf mutatja be, amelyek az enumerálás különböző értékeit használva keresik meg egy sztring utolsó előfordulását egy StringComparison másik sztringben.

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

Megjegyzések

Az indexszámozás nulláról indul. Ez azt jelenti, hogy a sztring első karaktere nulla, az utolsó Length pedig - 1.

A keresés a startIndex karakterhelyzetben kezdődik, és visszafelé halad, amíg meg value nem találja vagy meg nem vizsgálja az első karakter pozícióját. Ha például startIndexLength - 1, a metódus a sztring utolsó karakterétől az elejéig minden karaktert keres.

A comparisonType paraméter azt határozza meg, hogy a paramétert az value aktuális vagy az invariáns kultúra használatával, a kis- és nagybetűk megkülönböztetésével, a kis- és nagybetűk megkülönböztetésével, valamint a szórendi összehasonlító szabályok használatával keresse meg.

Megjegyzések a hívókhoz

A karakterkészletek figyelmen kívül hagyható karaktereket tartalmaznak, amelyek nyelvi vagy kulturális szempontból érzékeny összehasonlítások során nem figyelembe vett karakterek. Ha egy kulturális szempontból érzékeny keresésben (vagyis ha comparisonType nem Ordinal , vagy OrdinalIgnoreCase), ha value figyelmen kívül hagyható karaktert tartalmaz, akkor az eredmény egyenértékű az eltávolított karakterrel végzett kereséssel.

A következő példában a LastIndexOf(String, Int32, StringComparison) módszer egy puha kötőjel (U+00AD) pozíciójának megkeresésére szolgál, amelyet egy "m" követ, amely két sztringben az utolsó "m" karakterrel kezdődik. Csak az egyik sztring tartalmazza a szükséges részszűrést. Ha a példa .NET Framework 4-en vagy újabb verzióján fut, mindkét esetben, mivel a helyreállítható kötőjel egy figyelmen kívül hagyható karakter, a metódus az "m" indexét adja vissza a sztringben, amikor kulturális szempontból érzékeny összehasonlítást végez. Vegye figyelembe, hogy az első sztring esetében, amely magában foglalja a puha kötőjelet, majd az "m" értéket, a metódus az "m" indexét adja vissza, nem pedig a puha kötőjel indexét. A metódus csak akkor adja vissza a helyreállítható kötőjel indexét az első sztringben, ha a függvénydinális összehasonlítást végez.

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

A következőre érvényes:

LastIndexOf(String, Int32, Int32)

Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs

Egy adott sztring utolsó előfordulásának nullaalapú indexpozícióját jelenti ebben a példányban. A keresés egy megadott karakterhelyzetben kezdődik, és a sztring elején halad előre meghatározott számú karakterpozíció esetén.

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

Paraméterek

value
String

A keresendő sztring.

startIndex
Int32

A keresés kezdőpozíciója. A keresés a startIndex példány kezdetétől folytatódik.

count
Int32

A vizsgálandó karakterpozíciók száma.

Válaszok

A nulla alapú kezdőindex pozíciója value , ha a sztring található, vagy -1, ha nem található, vagy ha az aktuális példány egyenlő Empty.

Kivételek

value az null.

count negatív.

-vagy-

Az aktuális példány nem egyenlő Empty, és startIndex negatív.

-vagy-

Az aktuális példány nem egyenlő Empty, és startIndex nagyobb, mint a példány hossza.

-vagy-

Az aktuális példány nem egyenlő Empty, és startIndex - counta + 1 olyan pozíciót ad meg, amely nem ebben a példányban található.

-vagy-

Az aktuális példány egyenlő Empty , és startIndex kisebb, mint -1 vagy nagyobb, mint nulla.

-vagy-

Az aktuális példány egyenlő Empty , és count nagyobb, mint 1.

Példák

Az alábbi példa megkeresi egy sztring összes előfordulásának indexét az alsztringben, amely az alsztring végétől az alsztring elejéig működik.

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

Megjegyzések

Az indexszámozás nulláról indul. Ez azt jelenti, hogy a sztring első karaktere nulla, az utolsó Length pedig - 1.

A keresés a startIndex példány karakterpozíciójánál kezdődik, és visszafelé halad az elejéhez, amíg meg nem value találja count vagy meg nem vizsgálja a karakterpozíciókat. Ha például startIndexLength - 1, a metódus visszafelé count keres karaktereket a sztring utolsó karakteréből.

Ez a metódus egy szóalapú (kis- és nagybetűkre érzékeny) keresést hajt végre az aktuális kultúrával.

A karakterkészletek figyelmen kívül hagyható karaktereket tartalmaznak, amelyek nyelvi vagy kulturális szempontból érzékeny összehasonlítások során nem figyelembe vett karakterek. A kultúraérzékeny keresésekben, ha value figyelmen kívül hagyható karaktert tartalmaz, az eredmény egyenértékű az eltávolított karakterrel végzett kereséssel.

A következő példában a LastIndexOf módszer egy puha kötőjel (U+00AD) pozíciójának megkeresésére szolgál, majd egy "m" vagy "n" karaktert két sztringben. A sztringek közül csak az egyik tartalmaz puha kötőjelet. A helyreállítható kötőjelet és az "m" LastIndexOf karaktert tartalmazó sztring esetében az "m" indexét adja vissza a helyreállítható kötőjel és az "m" kifejezés keresésekor.

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

Megjegyzések a hívókhoz

A sztringek használatának ajánlott eljárásaiban leírtak szerint javasoljuk, hogy kerülje az alapértelmezett értékeket helyettesítő sztring-összehasonlító metódusok meghívását, és ne hívja meg azokat a metódusokat, amelyekhez paramétereket kell explicit módon megadni. Ha ezt a műveletet az aktuális kultúra összehasonlító szabályaival szeretné végrehajtani, a metódus paraméterének LastIndexOf(String, Int32, Int32, StringComparison) értékével való túlterhelésének meghívásával CurrentCulture jelezheti szándékát comparisonType explicit módon. Ha nincs szüksége nyelvtudó összehasonlításra, fontolja meg a használatát Ordinal.

Lásd még

A következőre érvényes:

LastIndexOf(Char, Int32, StringComparison)

Forrás:
String.Searching.cs
public:
 int LastIndexOf(char value, int startIndex, StringComparison comparisonType);
public int LastIndexOf(char value, int startIndex, StringComparison comparisonType);
member this.LastIndexOf : char * int * StringComparison -> int
Public Function LastIndexOf (value As Char, startIndex As Integer, comparisonType As StringComparison) As Integer

Paraméterek

value
Char
startIndex
Int32
comparisonType
StringComparison

Válaszok

A következőre érvényes:

LastIndexOf(Char, Int32, Int32)

Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs

A megadott Unicode-karakter utolsó előfordulásának nullaalapú indexpozícióját jelenti a példányon belüli alsztringben. A keresés egy megadott karakterhelyzetben kezdődik, és a sztring elején halad előre meghatározott számú karakterpozíció esetén.

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

Paraméterek

value
Char

A keresendő Unicode-karakter.

startIndex
Int32

A keresés kezdőpozíciója. A keresés a startIndex példány kezdetétől folytatódik.

count
Int32

A vizsgálandó karakterpozíciók száma.

Válaszok

A nulla alapú indexpozíció value , ha ez a karakter található, vagy -1, ha nem található, vagy ha az aktuális példány egyenlő Empty.

Kivételek

Az aktuális példány nem egyenlő Empty, és startIndex kisebb, mint nulla vagy nagyobb, mint a példány hossza.

-vagy-

Az aktuális példány nem egyenlő Empty, és startIndex - count a + 1 kisebb, mint nulla.

Példák

Az alábbi példa megkeresi egy karakter összes előfordulásának indexét egy alsztringben, amely az alsztring végétől az alsztring kezdetig működik.

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

Megjegyzések

Az indexszámozás nulláról indul. Ez azt jelenti, hogy a sztring első karaktere nulla, az utolsó Length pedig - 1.

Ez a metódus elkezd keresni a startIndex karakterhelyzetben, és a példány elejéhez visszafelé halad, amíg meg nem value találja count vagy meg nem vizsgálja a karakterpozíciókat. Ha például startIndexLength - 1, a metódus visszafelé count keres karaktereket a sztring utolsó karakteréből. A keresés megkülönbözteti a kis- és nagybetűkre vonatkozó adatokat.

Ez a módszer egy sorszámos (kulturális érzéketlen) keresést hajt végre, ahol egy karakter csak akkor tekinthető egyenértékűnek egy másik karakterrel, ha a Unicode skaláris értéke megegyezik. Kultúraérzékeny kereséshez használja azt a CompareInfo.LastIndexOf módszert, amelyben egy előre lefordított karaktert képviselő Unicode skaláris érték, például az "Æ" ligatúra (U+00C6) egyenértékűnek tekinthető a karakter összetevőinek a megfelelő sorrendben való előfordulásával, például az "AE" (U+0041, U+0045) értékkel, a kultúrától függően.

Lásd még

A következőre érvényes:

LastIndexOf(String, Int32)

Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs

Egy adott sztring utolsó előfordulásának nullaalapú indexpozícióját jelenti ebben a példányban. A keresés egy megadott karakterhelyzetben kezdődik, és a sztring elejéhez visszafelé halad.

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

Paraméterek

value
String

A keresendő sztring.

startIndex
Int32

A keresés kezdőpozíciója. A keresés a startIndex példány kezdetétől folytatódik.

Válaszok

A nulla alapú kezdőindex pozíciója value , ha a sztring található, vagy -1, ha nem található, vagy ha az aktuális példány egyenlő Empty.

Kivételek

value az null.

Az aktuális példány nem egyenlő Empty, és startIndex kisebb, mint nulla vagy nagyobb, mint az aktuális példány hossza.

-vagy-

Az aktuális példány egyenlő Empty, és startIndex kisebb, mint -1 vagy nagyobb, mint nulla.

Példák

Az alábbi példa megkeresi egy sztring összes előfordulásának indexét a célsztringben, és a célsztring végétől a célsztring elejéig dolgozik.

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

Megjegyzések

Az indexszámozás nulláról indul. Ez azt jelenti, hogy a sztring első karaktere nulla, az utolsó Length pedig - 1.

A keresés a startIndex példány karakterpozíciójánál kezdődik, és visszafelé halad, amíg meg nem value találja vagy meg nem vizsgálja az első karakter pozícióját. Ha például startIndexLength - 1, a metódus a sztring utolsó karakterétől az elejéig minden karaktert keres.

Ez a metódus egy szóalapú (kis- és nagybetűkre érzékeny) keresést hajt végre az aktuális kultúrával.

A karakterkészletek figyelmen kívül hagyható karaktereket tartalmaznak, amelyek nyelvi vagy kulturális szempontból érzékeny összehasonlítások során nem figyelembe vett karakterek. A kultúraérzékeny keresésekben, ha value figyelmen kívül hagyható karaktert tartalmaz, az eredmény egyenértékű az eltávolított karakterrel végzett kereséssel. A következő példában a LastIndexOf(String, Int32) metódus egy olyan részszúrást keres, amely egy puha kötőjelet (U+00AD) tartalmaz, és amely egy sztring utolsó "m" elemét előzi meg vagy tartalmazza. Ha a példa a .NET Framework 4 vagy újabb verzióján fut, mert a keresési sztringben a helyreállítható kötőjel figyelmen kívül van hagyva, a metódus meghívása a helyreállítható kötőjelből álló részsztring keresésére, az "m" pedig az "m" pozícióját adja vissza a sztringben, míg az "n" a helyreállítható kötőjelből álló alsztring megkeresésére, az "n" pedig az "n" pozícióját adja vissza.

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

Megjegyzések a hívókhoz

A sztringek használatának ajánlott eljárásaiban leírtak szerint javasoljuk, hogy kerülje az alapértelmezett értékeket helyettesítő sztring-összehasonlító metódusok meghívását, és ne hívja meg azokat a metódusokat, amelyekhez paramétereket kell explicit módon megadni. Ha egy adott karakterpozíciót megelőző alsztring indexét az aktuális kultúra összehasonlító szabályaival szeretné megkeresni, akkor a metódus túlterhelésének meghívásával LastIndexOf(String, Int32, StringComparison) jelezheti szándékát CurrentCulture a paraméter értékévelcomparisonType. Ha nincs szüksége nyelvtudó összehasonlításra, fontolja meg a használatát Ordinal.

Lásd még

A következőre érvényes:

LastIndexOf(Rune, Int32)

Forrás:
String.Searching.cs
public:
 int LastIndexOf(System::Text::Rune value, int startIndex);
public int LastIndexOf(System.Text.Rune value, int startIndex);
member this.LastIndexOf : System.Text.Rune * int -> int
Public Function LastIndexOf (value As Rune, startIndex As Integer) As Integer

Paraméterek

value
Rune
startIndex
Int32

Válaszok

A következőre érvényes:

LastIndexOf(String, StringComparison)

Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs

Egy adott sztring utolsó előfordulásának nulla alapú indexét jelenti az aktuális String objektumon belül. A paraméter megadja a megadott sztringhez használandó keresés típusát.

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

Paraméterek

value
String

A keresendő sztring.

comparisonType
StringComparison

A keresés szabályait meghatározó enumerálási értékek egyike.

Válaszok

A paraméter nullaalapú kezdőindex-pozíciója, ha ez a sztring value található, vagy -1, ha nem.

Kivételek

value az null.

comparisonType érvénytelen StringComparison érték.

Példák

Az alábbi példa a metódus három túlterhelését LastIndexOf mutatja be, amelyek az enumerálás különböző értékeit használva keresik meg egy sztring utolsó előfordulását egy StringComparison másik sztringben.

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

Megjegyzések

Az indexszámozás nulláról indul. Ez azt jelenti, hogy a sztring első karaktere nulla, az utolsó Length pedig - 1.

A comparisonType paraméter a következőkkel keresi meg a paramétert value :

  • A jelenlegi vagy invariáns kultúra.
  • Kis- és nagybetűk megkülönböztetése vagy érzéketlen keresés.
  • Word vagy a sorszámok összehasonlítására vonatkozó szabályokat.

A keresés a példány utolsó karakterpozíciójánál kezdődik, és visszafelé halad az elejéhez, amíg meg value nem találja vagy meg nem vizsgálja az első karakter pozícióját.

Megjegyzések a hívókhoz

A karakterkészletek figyelmen kívül hagyható karaktereket tartalmaznak, amelyek nyelvi vagy kulturális szempontból érzékeny összehasonlítások során nem figyelembe vett karakterek. Ha egy kulturális szempontból érzékeny keresésben (vagyis ha options nem Ordinal , vagy OrdinalIgnoreCase), ha value figyelmen kívül hagyható karaktert tartalmaz, akkor az eredmény egyenértékű az eltávolított karakterrel végzett kereséssel.

A következő példában a LastIndexOf(String, StringComparison) metódus két sztringet (egy puha kötőjelet, majd az "n" karaktert, egy puha kötőjelet, majd az "m") két sztringben található meg. A sztringek közül csak az egyik tartalmaz puha kötőjelet. Ha a példa a .NET Framework 4 vagy újabb verzióján fut, mivel a helyreállítható kötőjel egy figyelmen kívül hagyható karakter, a kultúraérzékeny keresés ugyanazt az értéket adja vissza, amelyet akkor ad vissza, ha a helyreállítható kötőjel nem szerepel a keresési sztringben. Az ordinális keresés azonban sikeresen megtalálta a helyreállítható kötőjelet egy sztringben, és azt jelenti, hogy hiányzik a második sztringből.

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

A következőre érvényes:

LastIndexOf(Rune, Int32, Int32, StringComparison)

Forrás:
String.Searching.cs
public:
 int LastIndexOf(System::Text::Rune value, int startIndex, int count, StringComparison comparisonType);
public int LastIndexOf(System.Text.Rune value, int startIndex, int count, StringComparison comparisonType);
member this.LastIndexOf : System.Text.Rune * int * int * StringComparison -> int
Public Function LastIndexOf (value As Rune, startIndex As Integer, count As Integer, comparisonType As StringComparison) As Integer

Paraméterek

value
Rune
startIndex
Int32
count
Int32
comparisonType
StringComparison

Válaszok

A következőre érvényes:

LastIndexOf(Char, StringComparison)

Forrás:
String.Searching.cs
public:
 int LastIndexOf(char value, StringComparison comparisonType);
public int LastIndexOf(char value, StringComparison comparisonType);
member this.LastIndexOf : char * StringComparison -> int
Public Function LastIndexOf (value As Char, comparisonType As StringComparison) As Integer

Paraméterek

value
Char
comparisonType
StringComparison

Válaszok

A következőre érvényes:

LastIndexOf(Char, Int32)

Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs

Egy megadott Unicode-karakter utolsó előfordulásának nullaalapú indexpozícióját jelenti ebben a példányban. A keresés egy megadott karakterhelyzetben kezdődik, és a sztring elejéhez visszafelé halad.

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

Paraméterek

value
Char

A keresendő Unicode-karakter.

startIndex
Int32

A keresés kezdőpozíciója. A keresés a startIndex példány kezdetétől folytatódik.

Válaszok

A nulla alapú indexpozíció value , ha ez a karakter található, vagy -1, ha nem található, vagy ha az aktuális példány egyenlő Empty.

Kivételek

Az aktuális példány nem egyenlő Empty, és startIndex kisebb, mint nulla vagy nagyobb, mint a példány hossza.

Példák

Az alábbi példa megkeresi egy sztringben egy karakter összes előfordulásának indexét, amely a sztring végétől a sztring elejéig működik.

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

Megjegyzések

Az indexszámozás nulláról indul. Ez azt jelenti, hogy a sztring első karaktere nulla, az utolsó Length pedig - 1. Ez a metódus elkezd keresni a startIndex példány karakterhelyzetében, és az aktuális példány elejéhez visszafelé halad, amíg meg nem value találja vagy meg nem vizsgálja az első karakterpozíciót. Ha például startIndexLength - 1, a metódus a sztring utolsó karakterétől az elejéig minden karaktert keres. A keresés megkülönbözteti a kis- és nagybetűkre vonatkozó adatokat.

Ez a módszer egy sorszámos (kulturális érzéketlen) keresést hajt végre, ahol egy karakter csak akkor tekinthető egyenértékűnek egy másik karakterrel, ha a Unicode skaláris értékei megegyeznek. Kultúraérzékeny kereséshez használja azt a CompareInfo.LastIndexOf módszert, amelyben egy előre lefordított karaktert képviselő Unicode skaláris érték, például az "Æ" ligatúra (U+00C6) egyenértékűnek tekinthető a karakter összetevőinek a megfelelő sorrendben való előfordulásával, például az "AE" (U+0041, U+0045) értékkel, a kultúrától függően.

Lásd még

A következőre érvényes:

LastIndexOf(Rune)

Forrás:
String.Searching.cs
public:
 int LastIndexOf(System::Text::Rune value);
public int LastIndexOf(System.Text.Rune value);
member this.LastIndexOf : System.Text.Rune -> int
Public Function LastIndexOf (value As Rune) As Integer

Paraméterek

value
Rune

Válaszok

A következőre érvényes:

LastIndexOf(String)

Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs

Egy adott sztring utolsó előfordulásának nullaalapú indexpozícióját jelenti ebben a példányban.

public:
 int LastIndexOf(System::String ^ value);
public int LastIndexOf(string value);
member this.LastIndexOf : string -> int
Public Function LastIndexOf (value As String) As Integer

Paraméterek

value
String

A keresendő sztring.

Válaszok

A nullaalapú kezdőindex pozíciója, ha a sztring value található, vagy -1, ha nem.

Kivételek

value az null.

Példák

Az alábbi példa eltávolítja a html-címkék megnyitását és bezárását egy sztringből, ha a címkék elkezdik és befejezik a sztringet. Ha egy sztring záró zárójel karakterrel (">" végződik), a példa a LastIndexOf metódussal megkeresi a végcímke elejét.

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>

Megjegyzések

Az indexszámozás nulláról indul. Ez azt jelenti, hogy a sztring első karaktere nulla, az utolsó Length pedig - 1.

A keresés a példány utolsó karakterpozíciójánál kezdődik, és visszafelé halad az elejéhez, amíg meg value nem találja vagy meg nem vizsgálja az első karakter pozícióját.

Ez a metódus egy szóalapú (kis- és nagybetűkre érzékeny) keresést hajt végre az aktuális kultúrával.

A karakterkészletek figyelmen kívül hagyható karaktereket tartalmaznak, amelyek nyelvi vagy kulturális szempontból érzékeny összehasonlítások során nem figyelembe vett karakterek. A kultúraérzékeny keresésekben, ha value figyelmen kívül hagyható karaktert tartalmaz, az eredmény egyenértékű az eltávolított karakterrel végzett kereséssel.

A következő példában a LastIndexOf(String) metódus két részsztringet (egy puha kötőjelet, majd az "n" és egy puha kötőjelet, majd az "m") két sztringben található meg. A sztringek közül csak az egyik tartalmaz puha kötőjelet. Ha a példa .NET Framework 4 vagy újabb verzióján fut, minden esetben, mivel a helyreállítható kötőjel figyelmen kívül hagyható karakter, az eredmény ugyanaz, mintha a helyreállítható kötőjel nem szerepel volna 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

Megjegyzések a hívókhoz

A sztringek használatának ajánlott eljárásaiban leírtak szerint javasoljuk, hogy kerülje az alapértelmezett értékeket helyettesítő sztring-összehasonlító metódusok meghívását, és ne hívja meg azokat a metódusokat, amelyekhez paramétereket kell explicit módon megadni. Ha egy sztringpéldányon belüli alsztring utolsó indexét az aktuális kultúra összehasonlító szabályainak használatával szeretné megtalálni, a metódus paraméterének LastIndexOf(String, StringComparison) értékével való túlterhelés meghívásával CurrentCulture jelezheti szándékát comparisonType explicit módon. Ha nincs szüksége nyelvtudó összehasonlításra, fontolja meg a használatát Ordinal.

Lásd még

A következőre érvényes:

LastIndexOf(Char)

Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs
Forrás:
String.Searching.cs

Egy megadott Unicode-karakter utolsó előfordulásának nullaalapú indexpozícióját jelenti ebben a példányban.

public:
 int LastIndexOf(char value);
public int LastIndexOf(char value);
member this.LastIndexOf : char -> int
Public Function LastIndexOf (value As Char) As Integer

Paraméterek

value
Char

A keresendő Unicode-karakter.

Válaszok

A nullaalapú index pozíciója value , ha ez a karakter található, vagy -1, ha nem.

Példák

Az alábbi példa egy metódust ExtractFilename határoz meg, amely a LastIndexOf(Char) metódus használatával megkeresi a karakterlánc utolsó könyvtárelválasztó karakterét, és kinyeri a sztring fájlnevét. Ha a fájl létezik, a metódus az elérési út nélkül adja vissza a fájlnevet.

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

Megjegyzések

Az indexszámozás nulláról indul. Ez azt jelenti, hogy a sztring első karaktere nulla, az utolsó Length pedig - 1.

Ez a metódus a példány utolsó karakterpozíciójában kezd keresni, és visszafelé halad az elejéhez, amíg meg nem value találja vagy meg nem vizsgálja az első karakterpozíciót. A keresés megkülönbözteti a kis- és nagybetűkre vonatkozó adatokat.

Ez a módszer egy sorszámos (kulturális érzéketlen) keresést hajt végre, ahol egy karakter csak akkor tekinthető egyenértékűnek egy másik karakterrel, ha a Unicode skaláris értékei megegyeznek. Kultúraérzékeny kereséshez használja azt a CompareInfo.LastIndexOf módszert, amelyben egy előre lefordított karaktert képviselő Unicode skaláris érték, például az "Æ" ligatúra (U+00C6) egyenértékűnek tekinthető a karakter összetevőinek a megfelelő sorrendben való előfordulásával, például az "AE" (U+0041, U+0045) értékkel, a kultúrától függően.

Lásd még

A következőre érvényes:

LastIndexOf(Rune, StringComparison)

Forrás:
String.Searching.cs
public:
 int LastIndexOf(System::Text::Rune value, StringComparison comparisonType);
public int LastIndexOf(System.Text.Rune value, StringComparison comparisonType);
member this.LastIndexOf : System.Text.Rune * StringComparison -> int
Public Function LastIndexOf (value As Rune, comparisonType As StringComparison) As Integer

Paraméterek

value
Rune
comparisonType
StringComparison

Válaszok

A következőre érvényes: