String.LastIndexOf Méthode

Définition

Signale la position d'index de base zéro de la dernière occurrence d'un caractère ou d'une chaîne Unicode spécifiés dans cette instance. La méthode retourne -1 si le caractère ou la chaîne est introuvable dans cette instance.

Surcharges

LastIndexOf(String, Int32, Int32, StringComparison)

Signale la position d'index de base zéro de la dernière occurrence d'une chaîne spécifiée dans cette instance. La recherche commence à une position de caractère spécifiée et se poursuit vers le début de la chaîne pour le nombre spécifié de positions de caractères. Un paramètre spécifie le type de comparaison à effectuer pendant la recherche de la chaîne spécifiée.

LastIndexOf(String, Int32, StringComparison)

Signale l'index de base zéro de la dernière occurrence d'une chaîne spécifiée dans l'objet String actuel. La recherche commence à une position de caractère spécifiée et se poursuit vers le début de la chaîne. Un paramètre spécifie le type de comparaison à effectuer pendant la recherche de la chaîne spécifiée.

LastIndexOf(String, Int32, Int32)

Signale la position d'index de base zéro de la dernière occurrence d'une chaîne spécifiée dans cette instance. La recherche commence à une position de caractère spécifiée et se poursuit vers le début de la chaîne pour un nombre spécifié de positions de caractères.

LastIndexOf(Char, Int32, Int32)

Signale la position d'index de base zéro de la dernière occurrence du caractère Unicode spécifié dans une sous-chaîne de cette instance. La recherche commence à une position de caractère spécifiée et se poursuit vers le début de la chaîne pour un nombre spécifié de positions de caractères.

LastIndexOf(String, Int32)

Signale la position d'index de base zéro de la dernière occurrence d'une chaîne spécifiée dans cette instance. La recherche commence à une position de caractère spécifiée et se poursuit vers le début de la chaîne.

LastIndexOf(Char, Int32)

Signale la position d'index de base zéro de la dernière occurrence d'un caractère Unicode spécifié dans cette instance. La recherche commence à une position de caractère spécifiée et se poursuit vers le début de la chaîne.

LastIndexOf(String)

Signale la position d'index de base zéro de la dernière occurrence d'une chaîne spécifiée dans cette instance.

LastIndexOf(Char)

Signale la position d'index de base zéro de la dernière occurrence d'un caractère Unicode spécifié dans cette instance.

LastIndexOf(String, StringComparison)

Signale l'index de base zéro de la dernière occurrence d'une chaîne spécifiée dans l'objet String actuel. Un paramètre spécifie le type de recherche à utiliser pour la chaîne spécifiée.

LastIndexOf(String, Int32, Int32, StringComparison)

Signale la position d'index de base zéro de la dernière occurrence d'une chaîne spécifiée dans cette instance. La recherche commence à une position de caractère spécifiée et se poursuit vers le début de la chaîne pour le nombre spécifié de positions de caractères. Un paramètre spécifie le type de comparaison à effectuer pendant la recherche de la chaîne spécifiée.

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ètres

value
String

Chaîne à rechercher.

startIndex
Int32

Position de départ de la recherche. La recherche se poursuit à partir de startIndex vers le début de cette instance.

count
Int32

Nombre de positions de caractère à examiner.

comparisonType
StringComparison

L'une des valeurs d'énumération qui spécifie les règles de la recherche.

Retours

Position d'index de départ de base zéro du paramètre value si cette chaîne est trouvée, ou -1 si elle est introuvable ou si l'instance actuelle est égale à Empty.

Exceptions

value a la valeur null.

count est un nombre négatif.

- ou -

L’instance actuelle n’est pas égale à Empty et startIndex est un nombre négatif.

- ou -

L’instance actuelle n’est pas égale à Empty et startIndex est supérieur à la longueur de cette instance.

- ou -

L’instance actuelle n’est pas égale à Empty et startIndex - count + 1 spécifie une position qui ne figure pas dans cette instance.

- ou -

L’instance actuelle est égale à Empty et start est inférieur à -1 ou supérieur à zéro.

- ou -

L’instance actuelle est égale à Empty et count est supérieur à 1.

comparisonType n’est pas une valeur de StringComparison valide.

Exemples

L’exemple suivant illustre trois surcharges de la LastIndexOf méthode qui recherchent la dernière occurrence d’une chaîne dans une autre chaîne à l’aide de différentes valeurs de l’énumération StringComparison .

// This code example demonstrates the 
// System.String.LastIndexOf(String, ..., StringComparison) methods.

using System;
using System.Threading;
using System.Globalization;

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the last occurrence of a character using different " + 
                   "values of StringComparison.";
    string resultFmt = "Comparison: {0,-28} Location: {1,3}";

// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
    string CapitalAWithRing = "\u00c5"; 

// Define a string to search. 
// The result of combining the characters LATIN SMALL LETTER A and COMBINING 
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character 
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
    string cat = "A Cheshire c" + "\u0061\u030a" + "t";
    int loc = 0;
    StringComparison[] scValues = {
        StringComparison.CurrentCulture,
        StringComparison.CurrentCultureIgnoreCase,
        StringComparison.InvariantCulture,
        StringComparison.InvariantCultureIgnoreCase,
        StringComparison.Ordinal,
        StringComparison.OrdinalIgnoreCase };

// Clear the screen and display an introduction.
    Console.Clear();
    Console.WriteLine(intro);

// Display the current culture because culture affects the result. For example, 
// try this code example with the "sv-SE" (Swedish-Sweden) culture.

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    Console.WriteLine("The current culture is \"{0}\" - {1}.", 
                       Thread.CurrentThread.CurrentCulture.Name,
                       Thread.CurrentThread.CurrentCulture.DisplayName);

// Display the string to search for and the string to search.
    Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"", 
                       CapitalAWithRing, cat);
    Console.WriteLine();

// Note that in each of the following searches, we look for 
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains 
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates 
// the string was not found.
// Search using different values of StringComparsion. Specify the start 
// index and count. 

    Console.WriteLine("Part 1: Start index and count are specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }

// Search using different values of StringComparsion. Specify the 
// start index. 
    Console.WriteLine("\nPart 2: Start index is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }

// Search using different values of StringComparsion. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.LastIndexOf(CapitalAWithRing, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }
    }
}

/*
Note: This code example was executed on a console whose user interface 
culture is "en-US" (English-United States).

This code example produces the following results:

Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

*/
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.

open System
open System.Threading
open System.Globalization

let intro = "Find the last occurrence of a character using different values of StringComparison."

// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let CapitalAWithRing = "\u00c5"

// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues = 
    [| StringComparison.CurrentCulture
       StringComparison.CurrentCultureIgnoreCase
       StringComparison.InvariantCulture
       StringComparison.InvariantCultureIgnoreCase
       StringComparison.Ordinal
       StringComparison.OrdinalIgnoreCase  |]

// Clear the screen and display an introduction.
Console.Clear()
printfn $"{intro}"

// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.

Thread.CurrentThread.CurrentCulture <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."

// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"

// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.

printfn "Part 1: Start index and count are specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).

This code example produces the following results:

Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

*)
' This code example demonstrates the 
' System.String.LastIndexOf(String, ..., StringComparison) methods.

Imports System.Threading
Imports System.Globalization

Class Sample
    Public Shared Sub Main() 
        Dim intro As String = "Find the last occurrence of a character using different " & _
                              "values of StringComparison."
        Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
        
        ' Define a string to search for.
        ' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
        Dim CapitalAWithRing As String = "Å"
        
        ' Define a string to search. 
        ' The result of combining the characters LATIN SMALL LETTER A and COMBINING 
        ' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character 
        ' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
        Dim cat As String = "A Cheshire c" & "å" & "t"
        Dim loc As Integer = 0
        Dim scValues As StringComparison() =  { _
                        StringComparison.CurrentCulture, _
                        StringComparison.CurrentCultureIgnoreCase, _
                        StringComparison.InvariantCulture, _
                        StringComparison.InvariantCultureIgnoreCase, _
                        StringComparison.Ordinal, _
                        StringComparison.OrdinalIgnoreCase }
        Dim sc As StringComparison
        
        ' Clear the screen and display an introduction.
        Console.Clear()
        Console.WriteLine(intro)
        
        ' Display the current culture because culture affects the result. For example, 
        ' try this code example with the "sv-SE" (Swedish-Sweden) culture.
        Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
        Console.WriteLine("The current culture is ""{0}"" - {1}.", _
                           Thread.CurrentThread.CurrentCulture.Name, _
                           Thread.CurrentThread.CurrentCulture.DisplayName)
        
        ' Display the string to search for and the string to search.
        Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
                           CapitalAWithRing, cat)
        Console.WriteLine()
        
        ' Note that in each of the following searches, we look for 
        ' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains 
        ' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates 
        ' the string was not found.
        ' Search using different values of StringComparsion. Specify the start 
        ' index and count. 
        Console.WriteLine("Part 1: Start index and count are specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparsion. Specify the 
        ' start index. 
        Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparsion. 
        Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
    
    End Sub
End Class

'
'Note: This code example was executed on a console whose user interface 
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the last occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'

Remarques

La numérotation d’index commence à partir de zéro. Autrement dit, le premier caractère de la chaîne est à l’index zéro et le dernier est à Length - 1.

La recherche commence à la position des caractères et se poursuit vers l’arrière startIndex jusqu’à ce que value soit trouvé ou count que les positions des caractères aient été examinées. Par exemple, si startIndex a la valeur Length - 1, la méthode recherche les caractères du count dernier caractère de la chaîne.

Le comparisonType paramètre spécifie de rechercher le paramètre à l’aide de value :

  • Culture actuelle ou invariante.
  • Recherche respectant la casse ou ne respectant pas la casse.
  • Word ou des règles de comparaison ordinales.

Notes pour les appelants

Les jeux de caractères incluent les caractères ignorables, à savoir les caractères qui ne sont pas considérés lors de l'exécution d'une comparaison linguistique ou dépendante de la culture. Dans une recherche dépendante de la culture (autrement dit, si comparisonType n'est pas Ordinal ou OrdinalIgnoreCase), si value contient un caractère ignorable, le résultat est équivalent à une recherche avec ce caractère supprimé.

Dans l’exemple suivant, la LastIndexOf(String, Int32, Int32, StringComparison) méthode est utilisée pour rechercher la position d’un trait d’union mou (U+00AD) suivi d’un « m » dans tous les caractères à l’exception du premier caractère avant le dernier « m » dans deux chaînes. Une seule des chaînes contient la sous-chaîne requise. Si l’exemple est exécuté sur .NET Framework 4 ou version ultérieure, dans les deux cas, parce que le trait d’union mou est un caractère ignoré, la méthode retourne l’index « m » dans la chaîne lorsqu’elle effectue une comparaison sensible à la culture. Toutefois, lorsqu’il effectue une comparaison ordinale, il trouve la sous-chaîne uniquement dans la première chaîne. Notez que dans le cas de la première chaîne, qui inclut le trait d’union mou suivi d’un « m », la méthode retourne l’index du « m » lorsqu’elle effectue une comparaison sensible à la culture. La méthode retourne l'index du trait d'union conditionnel dans la première chaîne uniquement lorsqu'elle effectue une comparaison ordinale.

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

S’applique à

LastIndexOf(String, Int32, StringComparison)

Signale l'index de base zéro de la dernière occurrence d'une chaîne spécifiée dans l'objet String actuel. La recherche commence à une position de caractère spécifiée et se poursuit vers le début de la chaîne. Un paramètre spécifie le type de comparaison à effectuer pendant la recherche de la chaîne spécifiée.

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ètres

value
String

Chaîne à rechercher.

startIndex
Int32

Position de départ de la recherche. La recherche se poursuit à partir de startIndex vers le début de cette instance.

comparisonType
StringComparison

L'une des valeurs d'énumération qui spécifie les règles de la recherche.

Retours

Position d'index de départ de base zéro du paramètre value si cette chaîne est trouvée, ou -1 si elle est introuvable ou si l'instance actuelle est égale à Empty.

Exceptions

value a la valeur null.

L’instance actuelle n’est pas égale à Empty, et startIndex est inférieur à zéro ou supérieur à la longueur de l’instance actuelle.

- ou -

L’instance actuelle est égale à Empty, et startIndex est inférieur à -1 ou supérieur à zéro.

comparisonType n’est pas une valeur de StringComparison valide.

Exemples

L’exemple suivant illustre trois surcharges de la LastIndexOf méthode qui recherchent la dernière occurrence d’une chaîne dans une autre chaîne à l’aide de différentes valeurs de l’énumération StringComparison .

// This code example demonstrates the 
// System.String.LastIndexOf(String, ..., StringComparison) methods.

using System;
using System.Threading;
using System.Globalization;

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the last occurrence of a character using different " + 
                   "values of StringComparison.";
    string resultFmt = "Comparison: {0,-28} Location: {1,3}";

// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
    string CapitalAWithRing = "\u00c5"; 

// Define a string to search. 
// The result of combining the characters LATIN SMALL LETTER A and COMBINING 
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character 
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
    string cat = "A Cheshire c" + "\u0061\u030a" + "t";
    int loc = 0;
    StringComparison[] scValues = {
        StringComparison.CurrentCulture,
        StringComparison.CurrentCultureIgnoreCase,
        StringComparison.InvariantCulture,
        StringComparison.InvariantCultureIgnoreCase,
        StringComparison.Ordinal,
        StringComparison.OrdinalIgnoreCase };

// Clear the screen and display an introduction.
    Console.Clear();
    Console.WriteLine(intro);

// Display the current culture because culture affects the result. For example, 
// try this code example with the "sv-SE" (Swedish-Sweden) culture.

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    Console.WriteLine("The current culture is \"{0}\" - {1}.", 
                       Thread.CurrentThread.CurrentCulture.Name,
                       Thread.CurrentThread.CurrentCulture.DisplayName);

// Display the string to search for and the string to search.
    Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"", 
                       CapitalAWithRing, cat);
    Console.WriteLine();

// Note that in each of the following searches, we look for 
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains 
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates 
// the string was not found.
// Search using different values of StringComparsion. Specify the start 
// index and count. 

    Console.WriteLine("Part 1: Start index and count are specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }

// Search using different values of StringComparsion. Specify the 
// start index. 
    Console.WriteLine("\nPart 2: Start index is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }

// Search using different values of StringComparsion. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.LastIndexOf(CapitalAWithRing, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }
    }
}

/*
Note: This code example was executed on a console whose user interface 
culture is "en-US" (English-United States).

This code example produces the following results:

Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

*/
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.

open System
open System.Threading
open System.Globalization

let intro = "Find the last occurrence of a character using different values of StringComparison."

// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let CapitalAWithRing = "\u00c5"

// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues = 
    [| StringComparison.CurrentCulture
       StringComparison.CurrentCultureIgnoreCase
       StringComparison.InvariantCulture
       StringComparison.InvariantCultureIgnoreCase
       StringComparison.Ordinal
       StringComparison.OrdinalIgnoreCase  |]

// Clear the screen and display an introduction.
Console.Clear()
printfn $"{intro}"

// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.

Thread.CurrentThread.CurrentCulture <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."

// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"

// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.

printfn "Part 1: Start index and count are specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).

This code example produces the following results:

Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

*)
' This code example demonstrates the 
' System.String.LastIndexOf(String, ..., StringComparison) methods.

Imports System.Threading
Imports System.Globalization

Class Sample
    Public Shared Sub Main() 
        Dim intro As String = "Find the last occurrence of a character using different " & _
                              "values of StringComparison."
        Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
        
        ' Define a string to search for.
        ' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
        Dim CapitalAWithRing As String = "Å"
        
        ' Define a string to search. 
        ' The result of combining the characters LATIN SMALL LETTER A and COMBINING 
        ' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character 
        ' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
        Dim cat As String = "A Cheshire c" & "å" & "t"
        Dim loc As Integer = 0
        Dim scValues As StringComparison() =  { _
                        StringComparison.CurrentCulture, _
                        StringComparison.CurrentCultureIgnoreCase, _
                        StringComparison.InvariantCulture, _
                        StringComparison.InvariantCultureIgnoreCase, _
                        StringComparison.Ordinal, _
                        StringComparison.OrdinalIgnoreCase }
        Dim sc As StringComparison
        
        ' Clear the screen and display an introduction.
        Console.Clear()
        Console.WriteLine(intro)
        
        ' Display the current culture because culture affects the result. For example, 
        ' try this code example with the "sv-SE" (Swedish-Sweden) culture.
        Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
        Console.WriteLine("The current culture is ""{0}"" - {1}.", _
                           Thread.CurrentThread.CurrentCulture.Name, _
                           Thread.CurrentThread.CurrentCulture.DisplayName)
        
        ' Display the string to search for and the string to search.
        Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
                           CapitalAWithRing, cat)
        Console.WriteLine()
        
        ' Note that in each of the following searches, we look for 
        ' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains 
        ' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates 
        ' the string was not found.
        ' Search using different values of StringComparsion. Specify the start 
        ' index and count. 
        Console.WriteLine("Part 1: Start index and count are specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparsion. Specify the 
        ' start index. 
        Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparsion. 
        Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
    
    End Sub
End Class

'
'Note: This code example was executed on a console whose user interface 
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the last occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'

Remarques

La numérotation d’index commence à partir de zéro. Autrement dit, le premier caractère de la chaîne est à l’index zéro et le dernier est à Length - 1.

La recherche commence à la position du caractère et se poursuit vers l’arrière startIndex jusqu’à ce que value soit trouvé ou que la position du premier caractère ait été examinée. Par exemple, si startIndex est Length - 1, la méthode recherche chaque caractère du dernier caractère de la chaîne au début.

Le comparisonType paramètre spécifie de rechercher le paramètre à l’aide de value la culture actuelle ou invariante, à l’aide d’une recherche respectant la casse ou respectant la casse, et à l’aide de règles de comparaison de mots ou ordinaux.

Notes pour les appelants

Les jeux de caractères incluent les caractères ignorables, à savoir les caractères qui ne sont pas considérés lors de l'exécution d'une comparaison linguistique ou dépendante de la culture. Dans une recherche dépendante de la culture (autrement dit, si comparisonType n'est pas Ordinal ou OrdinalIgnoreCase), si value contient un caractère ignorable, le résultat est équivalent à une recherche avec ce caractère supprimé.

Dans l’exemple suivant, la LastIndexOf(String, Int32, StringComparison) méthode est utilisée pour rechercher la position d’un trait d’union mou (U+00AD) suivi d’un « m », en commençant par le dernier « m » dans deux chaînes. Une seule des chaînes contient la sous-chaîne requise. Si l’exemple est exécuté sur .NET Framework 4 ou version ultérieure, dans les deux cas, parce que le trait d’union mou est un caractère ignoré, la méthode retourne l’index « m » dans la chaîne lorsqu’elle effectue une comparaison sensible à la culture. Notez que dans le cas de la première chaîne, qui inclut le trait d’union doux suivi d’un « m », la méthode retourne l’index du « m » et non l’index du trait d’union mou. La méthode retourne l'index du trait d'union conditionnel dans la première chaîne uniquement lorsqu'elle effectue une comparaison ordinale.

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

S’applique à

LastIndexOf(String, Int32, Int32)

Signale la position d'index de base zéro de la dernière occurrence d'une chaîne spécifiée dans cette instance. La recherche commence à une position de caractère spécifiée et se poursuit vers le début de la chaîne pour un nombre spécifié de positions de caractères.

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ètres

value
String

Chaîne à rechercher.

startIndex
Int32

Position de départ de la recherche. La recherche se poursuit à partir de startIndex vers le début de cette instance.

count
Int32

Nombre de positions de caractère à examiner.

Retours

Position d'index de départ de base zéro de value si cette chaîne est trouvée, ou -1 si elle est introuvable ou si l'instance actuelle est égale à Empty.

Exceptions

value a la valeur null.

count est un nombre négatif.

- ou -

L’instance actuelle n’est pas égale à Empty et startIndex est un nombre négatif.

- ou -

L’instance actuelle n’est pas égale à Empty et startIndex est supérieur à la longueur de cette instance.

- ou -

L’instance actuelle n’est pas égale à Empty et startIndex - count + 1 spécifie une position qui ne figure pas dans cette instance.

- ou -

L’instance actuelle est égale à Empty et start est inférieur à -1 ou supérieur à zéro.

- ou -

L’instance actuelle est égale à Empty et count est supérieur à 1.

Exemples

L’exemple suivant recherche l’index de toutes les occurrences d’une chaîne dans la sous-chaîne, allant de la fin de la sous-chaîne au début de la sous-chaîne.

// Sample for String::LastIndexOf(String, Int32, Int32)
using namespace System;
int main()
{
   String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
   String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
   String^ str = "Now is the time for all good men to come to the aid of their party.";
   int start;
   int at;
   int count;
   int end;
   start = str->Length - 1;
   end = start / 2 - 1;
   Console::WriteLine( "All occurrences of 'he' from position {0} to {1}.", start, end );
   Console::WriteLine( "{1}{0}{2}{0}{3}{0}", Environment::NewLine, br1, br2, str );
   Console::Write( "The string 'he' occurs at position(s): " );
   count = 0;
   at = 0;
   while ( (start > -1) && (at > -1) )
   {
      count = start - end; //Count must be within the substring.
      at = str->LastIndexOf( "he", start, count );
      if ( at > -1 )
      {
         Console::Write( "{0} ", at );
         start = at - 1;
      }
   }

   Console::Write( "{0} {0} {0}", Environment::NewLine );
}

/*
This example produces the following results:
All occurrences of 'he' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

The string 'he' occurs at position(s): 56 45
*/
// Sample for String.LastIndexOf(String, Int32, Int32)
using System;

class Sample {
    public static void Main() {

    string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
    string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
    string str = "Now is the time for all good men to come to the aid of their party.";
    int start;
    int at;
    int count;
    int end;

    start = str.Length-1;
    end = start/2 - 1;
    Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, end);
    Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
    Console.Write("The string 'he' occurs at position(s): ");

    count = 0;
    at = 0;
    while((start > -1) && (at > -1))
        {
        count = start - end; //Count must be within the substring.
        at = str.LastIndexOf("he", start, count);
        if (at > -1)
            {
            Console.Write("{0} ", at);
            start = at - 1;
            }
        }
    Console.Write("{0}{0}{0}", Environment.NewLine);
    }
}
/*
This example produces the following results:
All occurrences of 'he' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

The string 'he' occurs at position(s): 56 45
*/
// Sample for String.LastIndexOf(String, Int32, Int32)
open System

let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."

let mutable start = str.Length-1
let last = start / 2 - 1
printfn $"All occurrences of 'he' from position {start} to {last}."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The string 'he' occurs at position(s): "

let mutable at = 0
while (start > -1) && (at > -1) do
    let count = start - last //Count must be within the substring.
    at <- str.LastIndexOf("he", start, count)
    if at > -1 then
        printf $"{at} "
        start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 'he' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

The string 'he' occurs at position(s): 56 45
*)
' Sample for String.LastIndexOf(String, Int32, Int32)
 _

Class Sample
   
   Public Shared Sub Main()
      
      Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
      Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
      Dim str As String = "Now is the time for all good men to come to the aid of their party."
      Dim start As Integer
      Dim at As Integer
      Dim count As Integer
      Dim [end] As Integer

      start = str.Length - 1
      [end] = start / 2 - 1
      Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, [end])
      Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
      Console.Write("The string 'he' occurs at position(s): ")
      
      count = 0
      at = 0
      While start > - 1 And at > - 1
         count = start - [end] 'Count must be within the substring.
         at = str.LastIndexOf("he", start, count)
         If at > - 1 Then
            Console.Write("{0} ", at)
            start = at - 1
         End If
      End While
      Console.Write("{0}{0}{0}", Environment.NewLine)
   End Sub
End Class
'
'This example produces the following results:
'All occurrences of 'he' from position 66 to 32.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The string 'he' occurs at position(s): 56 45
'
'

Remarques

La numérotation d’index commence à partir de zéro. Autrement dit, le premier caractère de la chaîne est à l’index zéro et le dernier est à Length - 1.

La recherche commence à la startIndex position des caractères de ce instance et se poursuit vers l’arrière vers le début jusqu’à ce que value soit trouvé ou count que les positions des caractères aient été examinées. Par exemple, si startIndex a la valeur Length - 1, la méthode recherche les caractères du count dernier caractère de la chaîne.

Cette méthode effectue une recherche de mots (respectant la casse et la culture) à l’aide de la culture actuelle.

Les jeux de caractères incluent les caractères ignorables, à savoir les caractères qui ne sont pas considérés lors de l'exécution d'une comparaison linguistique ou dépendante de la culture. Dans une recherche dépendante de la culture, si value contient un caractère ignorable, le résultat est équivalent à la recherche avec ce caractère supprimé.

Dans l’exemple suivant, la LastIndexOf méthode est utilisée pour rechercher la position d’un trait d’union mou (U+00AD) suivi d’un « m » ou d’un « n » dans deux chaînes. Une seule des chaînes contient un trait d'union conditionnel. Dans le cas de la chaîne qui inclut le trait d’union doux suivi d’un « m », LastIndexOf retourne l’index du « m » lors de la recherche du trait d’union doux suivi de « m ».

int position = 0;
string s1 = "ani\u00ADmal";
string s2 = "animal";

// Find the index of the soft hyphen followed by "n".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s1.LastIndexOf("\u00ADn", position, position + 1));

position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s2.LastIndexOf("\u00ADn", position, position + 1));

// Find the index of the soft hyphen followed by "m".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s1.LastIndexOf("\u00ADm", position, position + 1));

position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s2.LastIndexOf("\u00ADm", position, position + 1));

// The example displays the following output:
//
// 'm' at position 4
// 1
// 'm' at position 3
// 1
// 'm' at position 4
// 4
// 'm' at position 3
// 3
let s1 = "ani\u00ADmal"
let s2 = "animal"

// Find the index of the soft hyphen followed by "n".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"

if position  >= 0 then
    printfn $"""{s1.LastIndexOf("\u00ADn", position, position + 1)}"""

let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"

if position  >= 0 then
    printfn $"""{s2.LastIndexOf("\u00ADn", position, position + 1)}"""

// Find the index of the soft hyphen followed by "m".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"

if position  >= 0 then
    printfn $"""{s1.LastIndexOf("\u00ADm", position, position + 1)}"""

let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"

if position  >= 0 then
    printfn $"""{s2.LastIndexOf("\u00ADm", position, position + 1)}"""

// The example displays the following output:
//
// 'm' at position 4
// 1
// 'm' at position 3
// 1
// 'm' at position 4
// 4
// 'm' at position 3
// 3
Dim position As Integer
Dim softHyphen As String = ChrW(&HAD)

Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"

' Find the index of the soft hyphen followed by "n".
position = s1.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")

If position >= 0 Then
    Console.WriteLine(s1.LastIndexOf(softHyphen + "n", position, position + 1))
End If

position = s2.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")

If position >= 0 Then
    Console.WriteLine(s2.LastIndexOf(softHyphen + "n", position, position + 1))
End If

' Find the index of the soft hyphen followed by "m".
position = s1.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")

If position >= 0 Then
    Console.WriteLine(s1.LastIndexOf(softHyphen + "m", position, position + 1))
End If

position = s2.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")

If position >= 0 Then
    Console.WriteLine(s2.LastIndexOf(softHyphen + "m", position, position + 1))
End If

' The example displays the following output:
'
' 'm' at position 4
' 1
' 'm' at position 3
' 1
' 'm' at position 4
' 4
' 'm' at position 3
' 3

Notes pour les appelants

Comme expliqué dans Meilleures pratiques pour l’utilisation de chaînes, nous vous recommandons d’éviter d’appeler des méthodes de comparaison de chaînes qui remplacent des valeurs par défaut et d’appeler plutôt des méthodes qui nécessitent des paramètres à spécifier explicitement. Pour effectuer cette opération à l’aide des règles de comparaison de la culture actuelle, signalez explicitement votre intention en appelant la LastIndexOf(String, Int32, Int32, StringComparison) surcharge de méthode avec la valeur pour CurrentCulture son comparisonType paramètre. Si vous n’avez pas besoin d’une comparaison linguistique, envisagez d’utiliser Ordinal.

Voir aussi

S’applique à

LastIndexOf(Char, Int32, Int32)

Signale la position d'index de base zéro de la dernière occurrence du caractère Unicode spécifié dans une sous-chaîne de cette instance. La recherche commence à une position de caractère spécifiée et se poursuit vers le début de la chaîne pour un nombre spécifié de positions de caractères.

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ètres

value
Char

Caractère Unicode à rechercher.

startIndex
Int32

Position de départ de la recherche. La recherche se poursuit à partir de startIndex vers le début de cette instance.

count
Int32

Nombre de positions de caractère à examiner.

Retours

Position d'index de base zéro de value si ce caractère est trouvé, ou -1 s'il est introuvable ou si l'instance actuelle est égale à Empty.

Exceptions

L’instance actuelle n’est pas égale à Empty et startIndex est inférieur à zéro ou supérieur ou égal à la longueur de cette instance.

- ou -

L’instance actuelle n’est pas égale à Empty et startIndex - count + 1 est inférieur à zéro.

Exemples

L’exemple suivant recherche l’index de toutes les occurrences d’un caractère dans une sous-chaîne, allant de la fin de la sous-chaîne au début de la sous-chaîne.

// Sample for String::LastIndexOf(Char, Int32, Int32)
using namespace System;
int main()
{
   String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
   String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
   String^ str = "Now is the time for all good men to come to the aid of their party.";
   int start;
   int at;
   int count;
   int end;
   start = str->Length - 1;
   end = start / 2 - 1;
   Console::WriteLine( "All occurrences of 't' from position {0} to {1}.", start, end );
   Console::WriteLine( "\n{0}\n{1}\n{2}", br1, br2, str );
   Console::Write( "The letter 't' occurs at position(s): " );
   count = 0;
   at = 0;
   while ( (start > -1) && (at > -1) )
   {
      count = start - end; //Count must be within the substring.
      at = str->LastIndexOf( 't', start, count );
      if ( at > -1 )
      {
         Console::Write( " {0} ", at );
         start = at - 1;
      }
   }
}

/*
This example produces the following results:
All occurrences of 't' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

The letter 't' occurs at position(s): 64 55 44 41 33


*/
// Sample for String.LastIndexOf(Char, Int32, Int32)
using System;

class Sample {
    public static void Main() {

    string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
    string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
    string str = "Now is the time for all good men to come to the aid of their party.";
    int start;
    int at;
    int count;
    int end;

    start = str.Length-1;
    end = start/2 - 1;
    Console.WriteLine("All occurrences of 't' from position {0} to {1}.", start, end);
    Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
    Console.Write("The letter 't' occurs at position(s): ");

    count = 0;
    at = 0;
    while((start > -1) && (at > -1))
        {
        count = start - end; //Count must be within the substring.
        at = str.LastIndexOf('t', start, count);
        if (at > -1)
            {
            Console.Write("{0} ", at);
            start = at - 1;
            }
        }
    Console.Write("{0}{0}{0}", Environment.NewLine);
    }
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

The letter 't' occurs at position(s): 64 55 44 41 33


*/
// Sample for String.LastIndexOf(Char, Int32, Int32)
open System

let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."

let mutable start = str.Length-1
let last = start / 2 - 1
printfn $"All occurrences of 't' from position {start} to {last}."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The letter 't' occurs at position(s): "

let mutable at = 0
while (start > -1) && (at > -1) do
    let count = start - last //Count must be within the substring.
    at <- str.LastIndexOf('t', start, count)
    if at > -1 then
        printf $"{at} "
        start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 't' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

The letter 't' occurs at position(s): 64 55 44 41 33


*)
' Sample for String.LastIndexOf(Char, Int32, Int32)
 _

Class Sample
   
   Public Shared Sub Main()
      
      Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
      Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
      Dim str As String = "Now is the time for all good men to come to the aid of their party."
      Dim start As Integer
      Dim at As Integer
      Dim count As Integer
      Dim [end] As Integer

      start = str.Length - 1
      [end] = start / 2 - 1
      Console.WriteLine("All occurrences of 't' from position {0} to {1}.", start, [end])
      Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
      Console.Write("The letter 't' occurs at position(s): ")
      
      count = 0
      at = 0
      While start > - 1 And at > - 1
         count = start - [end] 'Count must be within the substring.
         at = str.LastIndexOf("t"c, start, count)
         If at > - 1 Then
            Console.Write("{0} ", at)
            start = at - 1
         End If
      End While
      Console.Write("{0}{0}{0}", Environment.NewLine)
   End Sub
End Class
'
'This example produces the following results:
'All occurrences of 't' from position 66 to 32.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The letter 't' occurs at position(s): 64 55 44 41 33
'
'

Remarques

La numérotation d’index commence à partir de zéro. Autrement dit, le premier caractère de la chaîne est à l’index zéro et le dernier est à Length - 1.

Cette méthode commence la recherche à la position des startIndex caractères et se poursuit vers l’arrière vers le début de cette instance jusqu’à ce que value soit trouvé ou count que les positions des caractères aient été examinées. Par exemple, si startIndex a la valeur Length - 1, la méthode recherche les caractères du count dernier caractère de la chaîne. La recherche respecte la casse.

Cette méthode effectue une recherche ordinale (insensible à la culture), où un caractère est considéré comme équivalent à un autre caractère uniquement si sa valeur scalaire Unicode est identique. Pour effectuer une recherche sensible à la culture, utilisez la CompareInfo.LastIndexOf méthode, où une valeur scalaire Unicode représentant un caractère précomposé, comme la ligature « Æ » (U+00C6), peut être considérée comme équivalente à toute occurrence des composants du caractère dans la séquence appropriée, telle que « AE » (U+0041, U+0045), selon la culture.

Voir aussi

S’applique à

LastIndexOf(String, Int32)

Signale la position d'index de base zéro de la dernière occurrence d'une chaîne spécifiée dans cette instance. La recherche commence à une position de caractère spécifiée et se poursuit vers le début de la chaîne.

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ètres

value
String

Chaîne à rechercher.

startIndex
Int32

Position de départ de la recherche. La recherche se poursuit à partir de startIndex vers le début de cette instance.

Retours

Position d'index de départ de base zéro de value si cette chaîne est trouvée, ou -1 si elle est introuvable ou si l'instance actuelle est égale à Empty.

Exceptions

value a la valeur null.

L’instance actuelle n’est pas égale à Empty, et startIndex est inférieur à zéro ou supérieur à la longueur de l’instance actuelle.

- ou -

L’instance actuelle est égale à Empty, et startIndex est inférieur à -1 ou supérieur à zéro.

Exemples

L’exemple suivant recherche l’index de toutes les occurrences d’une chaîne dans la chaîne cible, allant de la fin de la chaîne cible au début de la chaîne cible.

// Sample for String::LastIndexOf(String, Int32)
using namespace System;
int main()
{
   String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
   String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
   String^ str = "Now is the time for all good men to come to the aid of their party.";
   int start;
   int at;
   start = str->Length - 1;
   Console::WriteLine( "All occurrences of 'he' from position {0} to 0.", start );
   Console::WriteLine( "{0}\n{1}\n{2}\n", br1, br2, str );
   Console::Write( "The string 'he' occurs at position(s): " );
   at = 0;
   while ( (start > -1) && (at > -1) )
   {
      at = str->LastIndexOf( "he", start );
      if ( at > -1 )
      {
         Console::Write( " {0} ", at );
         start = at - 1;
      }
   }

   Console::WriteLine();
}

/*
This example produces the following results:
All occurrences of 'he' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

The string 'he' occurs at position(s):  56  45  8
*/
// Sample for String.LastIndexOf(String, Int32)
using System;

class Sample {
    public static void Main() {

    string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
    string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
    string str = "Now is the time for all good men to come to the aid of their party.";
    int start;
    int at;

    start = str.Length-1;
    Console.WriteLine("All occurrences of 'he' from position {0} to 0.", start);
    Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
    Console.Write("The string 'he' occurs at position(s): ");

    at = 0;
    while((start > -1) && (at > -1))
        {
        at = str.LastIndexOf("he", start);
        if (at > -1)
            {
            Console.Write("{0} ", at);
            start = at - 1;
            }
        }
    Console.Write("{0}{0}{0}", Environment.NewLine);
    }
}
/*
This example produces the following results:
All occurrences of 'he' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

The string 'he' occurs at position(s): 56 45 8


*/
// Sample for String.LastIndexOf(String, Int32)
open System

let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."

let mutable start = str.Length - 1
printfn $"All occurrences of 'he' from position {start} to 0." 
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The string 'he' occurs at position(s): "

let mutable at = 0
while (start > -1) && (at > -1) do
    at <- str.LastIndexOf("he", start)
    if at > -1 then
        printf $"{at} "
        start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 'he' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

The string 'he' occurs at position(s): 56 45 8


*)
' Sample for String.LastIndexOf(String, Int32)
 _

Class Sample
   
   Public Shared Sub Main()
      
      Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
      Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
      Dim str As String = "Now is the time for all good men to come to the aid of their party."
      Dim start As Integer
      Dim at As Integer

      '#3
      start = str.Length - 1
      Console.WriteLine("All occurrences of 'he' from position {0} to 0.", start)
      Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
      Console.Write("The string 'he' occurs at position(s): ")
      
      at = 0
      While start > - 1 And at > - 1
         at = str.LastIndexOf("he", start)
         If at > - 1 Then
            Console.Write("{0} ", at)
            start = at - 1
         End If
      End While
      Console.Write("{0}{0}{0}", Environment.NewLine)
   End Sub
End Class
'
'This example produces the following results:
'All occurrences of 'he' from position 66 to 0.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The string 'he' occurs at position(s): 56 45 8
'
'

Remarques

La numérotation d’index commence à partir de zéro. Autrement dit, le premier caractère de la chaîne est à l’index zéro et le dernier est à Length - 1.

La recherche commence à la startIndex position des caractères de cette instance et se poursuit vers l’arrière jusqu’à ce que value soit trouvé ou que la position du premier caractère ait été examinée. Par exemple, si startIndex est Length - 1, la méthode recherche chaque caractère du dernier caractère de la chaîne au début.

Cette méthode effectue une recherche de mots (respectant la casse et la culture) à l’aide de la culture actuelle.

Les jeux de caractères incluent les caractères ignorables, à savoir les caractères qui ne sont pas considérés lors de l'exécution d'une comparaison linguistique ou dépendante de la culture. Dans une recherche dépendante de la culture, si value contient un caractère ignorable, le résultat est équivalent à la recherche avec ce caractère supprimé. Dans l’exemple suivant, la LastIndexOf(String, Int32) méthode est utilisée pour rechercher une sous-chaîne qui comprend un trait d’union mou (U+00AD) et qui précède ou inclut le « m » final dans une chaîne. Si l’exemple est exécuté sur .NET Framework 4 ou version ultérieure, car le trait d’union mou dans la chaîne de recherche est ignoré, l’appel de la méthode pour rechercher une sous-chaîne qui se compose du trait d’union mou et « m » renvoie la position du « m » dans la chaîne, tandis que l’appel de celui-ci pour rechercher une sous-chaîne qui se compose du trait d’union doux et « n » renvoie la position du « n ».

int position = 0;
string s1 = "ani\u00ADmal";
string s2 = "animal";

// Find the index of the soft hyphen followed by "n".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s1.LastIndexOf("\u00ADn", position));

position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s2.LastIndexOf("\u00ADn", position));

// Find the index of the soft hyphen followed by "m".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s1.LastIndexOf("\u00ADm", position));

position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");

if (position >= 0)
    Console.WriteLine(s2.LastIndexOf("\u00ADm", position));

// The example displays the following output:
//
// 'm' at position 4
// 1
// 'm' at position 3
// 1
// 'm' at position 4
// 4
// 'm' at position 3
// 3
let s1 = "ani\u00ADmal"
let s2 = "animal"

// Find the index of the soft hyphen followed by "n".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"

if position >= 0 then
    printfn $"""{s1.LastIndexOf("\u00ADn", position)}"""

let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"

if position >= 0 then
    printfn $"""{s2.LastIndexOf("\u00ADn", position)}"""

// Find the index of the soft hyphen followed by "m".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"

if position >= 0 then
    printfn $"""{s1.LastIndexOf("\u00ADm", position)}"""

let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"

if position >= 0 then
    printfn $"""{s2.LastIndexOf("\u00ADm", position)}"""
// The example displays the following output:
//
// 'm' at position 4
// 1
// 'm' at position 3
// 1
// 'm' at position 4
// 4
// 'm' at position 3
// 3
Dim position As Integer
Dim softHyphen As String = ChrW(&HAD)
Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"

' Find the index of the soft hyphen followed by "n".
position = s1.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")

If position >= 0 Then
    Console.WriteLine(s1.LastIndexOf(softHyphen + "n", position))
End If

position = s2.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")

If position >= 0 Then
    Console.WriteLine(s2.LastIndexOf(softHyphen + "n", position))
End If

' Find the index of the soft hyphen followed by "m".
position = s1.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")

If position >= 0 Then
    Console.WriteLine(s1.LastIndexOf(softHyphen + "m", position))
End If

position = s2.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")

If position >= 0 Then
    Console.WriteLine(s2.LastIndexOf(softHyphen + "m", position))
End If

' The example displays the following output:
'
' 'm' at position 4
' 1
' 'm' at position 3
' 1
' 'm' at position 4
' 4
' 'm' at position 3
' 3

Notes pour les appelants

Comme expliqué dans Meilleures pratiques pour l’utilisation de chaînes, nous vous recommandons d’éviter d’appeler des méthodes de comparaison de chaînes qui remplacent des valeurs par défaut et d’appeler plutôt des méthodes qui nécessitent des paramètres à spécifier explicitement. Pour rechercher l’index d’une sous-chaîne qui précède une position de caractère particulière à l’aide des règles de comparaison de la culture actuelle, signalez explicitement votre intention en appelant la surcharge de méthode LastIndexOf(String, Int32, StringComparison) avec une valeur de CurrentCulture pour son comparisonType paramètre. Si vous n’avez pas besoin d’une comparaison linguistique, envisagez d’utiliser Ordinal.

Voir aussi

S’applique à

LastIndexOf(Char, Int32)

Signale la position d'index de base zéro de la dernière occurrence d'un caractère Unicode spécifié dans cette instance. La recherche commence à une position de caractère spécifiée et se poursuit vers le début de la chaîne.

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ètres

value
Char

Caractère Unicode à rechercher.

startIndex
Int32

Position de départ de la recherche. La recherche se poursuit à partir de startIndex vers le début de cette instance.

Retours

Position d'index de base zéro de value si ce caractère est trouvé, ou -1 s'il est introuvable ou si l'instance actuelle est égale à Empty.

Exceptions

L’instance actuelle n’est pas égale à Empty et startIndex est inférieur à zéro ou supérieur ou égal à la longueur de cette instance.

Exemples

L’exemple suivant recherche l’index de toutes les occurrences d’un caractère dans une chaîne, allant de la fin de la chaîne au début de la chaîne.

// Sample for String::LastIndexOf(Char, Int32)
using namespace System;
int main()
{
   String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
   String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
   String^ str = "Now is the time for all good men to come to the aid of their party.";
   int start;
   int at;
   start = str->Length - 1;
   Console::WriteLine( "All occurrences of 't' from position {0} to 0.", start );
   Console::WriteLine( "{0}\n{1}\n{2}\n", br1, br2, str );
   Console::Write( "The letter 't' occurs at position(s): " );
   at = 0;
   while ( (start > -1) && (at > -1) )
   {
      at = str->LastIndexOf( 't', start );
      if ( at > -1 )
      {
         Console::Write( " {0} ", at );
         start = at - 1;
      }
   }
}

/*
This example produces the following results:
All occurrences of 't' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

The letter 't' occurs at position(s): 64 55 44 41 33 11 7
*/
// Sample for String.LastIndexOf(Char, Int32)
using System;

class Sample {
    public static void Main() {

    string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
    string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
    string str = "Now is the time for all good men to come to the aid of their party.";
    int start;
    int at;

    start = str.Length-1;
    Console.WriteLine("All occurrences of 't' from position {0} to 0.", start);
    Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
    Console.Write("The letter 't' occurs at position(s): ");

    at = 0;
    while((start > -1) && (at > -1))
        {
        at = str.LastIndexOf('t', start);
        if (at > -1)
            {
            Console.Write("{0} ", at);
            start = at - 1;
            }
        }
    Console.Write("{0}{0}{0}", Environment.NewLine);
    }
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

The letter 't' occurs at position(s): 64 55 44 41 33 11 7
*/
// Sample for String.LastIndexOf(Char, Int32)
open System

let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."

let mutable start = str.Length - 1
printfn $"All occurrences of 't' from position {start} to 0."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The letter 't' occurs at position(s): "

let mutable at = 0
while (start > -1) && (at > -1) do
    at <- str.LastIndexOf('t', start)
    if at > -1 then
        printf $"{at} "
        start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 't' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

The letter 't' occurs at position(s): 64 55 44 41 33 11 7
*)
' Sample for String.LastIndexOf(Char, Int32)
Imports System 
 _

Class Sample
   
   Public Shared Sub Main()
      
      Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
      Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
      Dim str As String = "Now is the time for all good men to come to the aid of their party."
      Dim start As Integer
      Dim at As Integer
      
      start = str.Length - 1
      Console.WriteLine("All occurrences of 't' from position {0} to 0.", start)
      Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
      Console.Write("The letter 't' occurs at position(s): ")
      
      at = 0
      While start > - 1 And at > - 1
         at = str.LastIndexOf("t"c, start)
         If at > - 1 Then
            Console.Write("{0} ", at)
            start = at - 1
         End If
      End While
      Console.Write("{0}{0}{0}", Environment.NewLine)
   End Sub
End Class
'
'This example produces the following results:
'All occurrences of 't' from position 66 to 0.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The letter 't' occurs at position(s): 64 55 44 41 33 11 7
'

Remarques

La numérotation d’index commence à partir de zéro. Autrement dit, le premier caractère de la chaîne est à l’index zéro et le dernier est à Length - 1. Cette méthode commence la recherche à la startIndex position des caractères de cette instance et se poursuit vers l’arrière vers le début de la instance actuelle jusqu’à ce que value soit trouvé ou que la position du premier caractère ait été examinée. Par exemple, si startIndex est Length - 1, la méthode recherche chaque caractère du dernier caractère de la chaîne au début. La recherche respecte la casse.

Cette méthode effectue une recherche ordinale (insensible à la culture), où un caractère est considéré comme équivalent à un autre caractère uniquement si ses valeurs scalaires Unicode sont identiques. Pour effectuer une recherche sensible à la culture, utilisez la CompareInfo.LastIndexOf méthode, où une valeur scalaire Unicode représentant un caractère précomposé, comme la ligature « Æ » (U+00C6), peut être considérée comme équivalente à toute occurrence des composants du caractère dans la séquence appropriée, telle que « AE » (U+0041, U+0045), selon la culture.

Voir aussi

S’applique à

LastIndexOf(String)

Signale la position d'index de base zéro de la dernière occurrence d'une chaîne spécifiée dans cette instance.

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ètres

value
String

Chaîne à rechercher.

Retours

Position d'index de départ de base zéro de value si cette chaîne est disponible ou -1 si elle est introuvable.

Exceptions

value a la valeur null.

Exemples

L’exemple suivant supprime les balises HTML ouvrantes et fermant d’une chaîne si les balises commencent et terminent la chaîne. Si une chaîne se termine par un caractère entre crochets fermant (« > »), l’exemple utilise la LastIndexOf méthode pour localiser le début de la balise de fin.

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>

Remarques

La numérotation d’index commence à partir de zéro. Autrement dit, le premier caractère de la chaîne est à l’index zéro et le dernier est à Length - 1.

La recherche commence à la dernière position de caractère de cette instance et se poursuit vers l’arrière jusqu’au début jusqu’à ce que value soit trouvé ou que la première position du caractère ait été examinée.

Cette méthode effectue une recherche de mots (respectant la casse et la culture) à l’aide de la culture actuelle.

Les jeux de caractères incluent les caractères ignorables, à savoir les caractères qui ne sont pas considérés lors de l'exécution d'une comparaison linguistique ou dépendante de la culture. Dans une recherche dépendante de la culture, si value contient un caractère ignorable, le résultat est équivalent à la recherche avec ce caractère supprimé.

Dans l’exemple suivant, la LastIndexOf(String) méthode est utilisée pour rechercher deux sous-chaînes (un trait d’union doux suivi de « n » et un trait d’union doux suivi de « m ») dans deux chaînes. Une seule des chaînes contient un trait d'union conditionnel. Si l’exemple est exécuté sur .NET Framework 4 ou version ultérieure, dans chaque cas, parce que le trait d’union mou est un caractère ignorant, le résultat est le même que si le trait d’union doux n’avait pas été inclus dans 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

Notes pour les appelants

Comme expliqué dans Meilleures pratiques pour l’utilisation de chaînes, nous vous recommandons d’éviter d’appeler des méthodes de comparaison de chaînes qui remplacent des valeurs par défaut et d’appeler plutôt des méthodes qui nécessitent des paramètres à spécifier explicitement. Pour rechercher le dernier index d’une sous-chaîne au sein d’une chaîne instance à l’aide des règles de comparaison de la culture actuelle, signalez explicitement votre intention en appelant la LastIndexOf(String, StringComparison) surcharge de méthode avec une valeur de CurrentCulture pour son comparisonType paramètre. Si vous n’avez pas besoin d’une comparaison linguistique, envisagez d’utiliser Ordinal.

Voir aussi

S’applique à

LastIndexOf(Char)

Signale la position d'index de base zéro de la dernière occurrence d'un caractère Unicode spécifié dans cette instance.

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

Paramètres

value
Char

Caractère Unicode à rechercher.

Retours

Position d'index de base zéro de value si ce caractère est disponible ou -1 s'il est introuvable.

Exemples

L’exemple suivant définit une ExtractFilename méthode qui utilise la LastIndexOf(Char) méthode pour rechercher le dernier caractère séparateur de répertoire dans une chaîne et extraire le nom de fichier de la chaîne. Si le fichier existe, la méthode retourne le nom du fichier sans son chemin d’accès.

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

Remarques

La numérotation d’index commence à partir de zéro. Autrement dit, le premier caractère de la chaîne est à l’index zéro et le dernier est à Length - 1.

Cette méthode commence la recherche à la dernière position de caractère de cette instance et continue vers l’arrière vers le début jusqu’à ce que value soit trouvé ou que la première position de caractère ait été examinée. La recherche respecte la casse.

Cette méthode effectue une recherche ordinale (insensible à la culture), où un caractère est considéré comme équivalent à un autre caractère uniquement si ses valeurs scalaires Unicode sont identiques. Pour effectuer une recherche sensible à la culture, utilisez la CompareInfo.LastIndexOf méthode, où une valeur scalaire Unicode représentant un caractère précomposé, comme la ligature « Æ » (U+00C6), peut être considérée comme équivalente à toute occurrence des composants du caractère dans la séquence appropriée, telle que « AE » (U+0041, U+0045), selon la culture.

Voir aussi

S’applique à

LastIndexOf(String, StringComparison)

Signale l'index de base zéro de la dernière occurrence d'une chaîne spécifiée dans l'objet String actuel. Un paramètre spécifie le type de recherche à utiliser pour la chaîne spécifiée.

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ètres

value
String

Chaîne à rechercher.

comparisonType
StringComparison

L'une des valeurs d'énumération qui spécifie les règles de la recherche.

Retours

Position de départ d'index de base zéro du paramètre value si cette chaîne est disponible ou -1 si elle est introuvable.

Exceptions

value a la valeur null.

comparisonType n’est pas une valeur de StringComparison valide.

Exemples

L’exemple suivant illustre trois surcharges de la LastIndexOf méthode qui recherchent la dernière occurrence d’une chaîne dans une autre chaîne à l’aide de différentes valeurs de l’énumération StringComparison .

// This code example demonstrates the 
// System.String.LastIndexOf(String, ..., StringComparison) methods.

using System;
using System.Threading;
using System.Globalization;

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the last occurrence of a character using different " + 
                   "values of StringComparison.";
    string resultFmt = "Comparison: {0,-28} Location: {1,3}";

// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
    string CapitalAWithRing = "\u00c5"; 

// Define a string to search. 
// The result of combining the characters LATIN SMALL LETTER A and COMBINING 
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character 
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
    string cat = "A Cheshire c" + "\u0061\u030a" + "t";
    int loc = 0;
    StringComparison[] scValues = {
        StringComparison.CurrentCulture,
        StringComparison.CurrentCultureIgnoreCase,
        StringComparison.InvariantCulture,
        StringComparison.InvariantCultureIgnoreCase,
        StringComparison.Ordinal,
        StringComparison.OrdinalIgnoreCase };

// Clear the screen and display an introduction.
    Console.Clear();
    Console.WriteLine(intro);

// Display the current culture because culture affects the result. For example, 
// try this code example with the "sv-SE" (Swedish-Sweden) culture.

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    Console.WriteLine("The current culture is \"{0}\" - {1}.", 
                       Thread.CurrentThread.CurrentCulture.Name,
                       Thread.CurrentThread.CurrentCulture.DisplayName);

// Display the string to search for and the string to search.
    Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"", 
                       CapitalAWithRing, cat);
    Console.WriteLine();

// Note that in each of the following searches, we look for 
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains 
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates 
// the string was not found.
// Search using different values of StringComparsion. Specify the start 
// index and count. 

    Console.WriteLine("Part 1: Start index and count are specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }

// Search using different values of StringComparsion. Specify the 
// start index. 
    Console.WriteLine("\nPart 2: Start index is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }

// Search using different values of StringComparsion. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.LastIndexOf(CapitalAWithRing, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }
    }
}

/*
Note: This code example was executed on a console whose user interface 
culture is "en-US" (English-United States).

This code example produces the following results:

Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

*/
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.

open System
open System.Threading
open System.Globalization

let intro = "Find the last occurrence of a character using different values of StringComparison."

// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let CapitalAWithRing = "\u00c5"

// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues = 
    [| StringComparison.CurrentCulture
       StringComparison.CurrentCultureIgnoreCase
       StringComparison.InvariantCulture
       StringComparison.InvariantCultureIgnoreCase
       StringComparison.Ordinal
       StringComparison.OrdinalIgnoreCase  |]

// Clear the screen and display an introduction.
Console.Clear()
printfn $"{intro}"

// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.

Thread.CurrentThread.CurrentCulture <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."

// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"

// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.

printfn "Part 1: Start index and count are specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
    let loc = cat.LastIndexOf(CapitalAWithRing, sc)
    printfn $"Comparison: {sc,-28} Location: {loc,3}"

(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).

This code example produces the following results:

Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

*)
' This code example demonstrates the 
' System.String.LastIndexOf(String, ..., StringComparison) methods.

Imports System.Threading
Imports System.Globalization

Class Sample
    Public Shared Sub Main() 
        Dim intro As String = "Find the last occurrence of a character using different " & _
                              "values of StringComparison."
        Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
        
        ' Define a string to search for.
        ' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
        Dim CapitalAWithRing As String = "Å"
        
        ' Define a string to search. 
        ' The result of combining the characters LATIN SMALL LETTER A and COMBINING 
        ' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character 
        ' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
        Dim cat As String = "A Cheshire c" & "å" & "t"
        Dim loc As Integer = 0
        Dim scValues As StringComparison() =  { _
                        StringComparison.CurrentCulture, _
                        StringComparison.CurrentCultureIgnoreCase, _
                        StringComparison.InvariantCulture, _
                        StringComparison.InvariantCultureIgnoreCase, _
                        StringComparison.Ordinal, _
                        StringComparison.OrdinalIgnoreCase }
        Dim sc As StringComparison
        
        ' Clear the screen and display an introduction.
        Console.Clear()
        Console.WriteLine(intro)
        
        ' Display the current culture because culture affects the result. For example, 
        ' try this code example with the "sv-SE" (Swedish-Sweden) culture.
        Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
        Console.WriteLine("The current culture is ""{0}"" - {1}.", _
                           Thread.CurrentThread.CurrentCulture.Name, _
                           Thread.CurrentThread.CurrentCulture.DisplayName)
        
        ' Display the string to search for and the string to search.
        Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
                           CapitalAWithRing, cat)
        Console.WriteLine()
        
        ' Note that in each of the following searches, we look for 
        ' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains 
        ' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates 
        ' the string was not found.
        ' Search using different values of StringComparsion. Specify the start 
        ' index and count. 
        Console.WriteLine("Part 1: Start index and count are specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparsion. Specify the 
        ' start index. 
        Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparsion. 
        Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
        For Each sc In  scValues
            loc = cat.LastIndexOf(CapitalAWithRing, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
    
    End Sub
End Class

'
'Note: This code example was executed on a console whose user interface 
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the last occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'

Remarques

La numérotation d’index commence à partir de zéro. Autrement dit, le premier caractère de la chaîne est à l’index zéro et le dernier est à Length - 1.

Le comparisonType paramètre spécifie de rechercher le paramètre à l’aide de value :

  • Culture actuelle ou invariante.
  • Recherche respectant la casse ou ne respectant pas la casse.
  • Word ou des règles de comparaison ordinales.

La recherche commence à la dernière position de caractère de cette instance et se poursuit vers l’arrière jusqu’au début jusqu’à ce que value soit trouvé ou que la première position du caractère ait été examinée.

Notes pour les appelants

Les jeux de caractères incluent les caractères ignorables, à savoir les caractères qui ne sont pas considérés lors de l'exécution d'une comparaison linguistique ou dépendante de la culture. Dans une recherche dépendante de la culture (autrement dit, si options n'est pas Ordinal ou OrdinalIgnoreCase), si value contient un caractère ignorable, le résultat est équivalent à une recherche avec ce caractère supprimé.

Dans l’exemple suivant, la LastIndexOf(String, StringComparison) méthode est utilisée pour rechercher deux sous-chaînes (un trait d’union doux suivi de « n » et un trait d’union doux suivi de « m ») dans deux chaînes. Une seule des chaînes contient un trait d'union conditionnel. Si l’exemple est exécuté sur .NET Framework 4 ou version ultérieure, parce que le trait d’union mou est un caractère ignoré, une recherche sensible à la culture renvoie la même valeur qu’elle retournerait si le trait d’union souple n’était pas inclus dans la chaîne de recherche. Une recherche ordinale, cependant, trouve le trait d’union mou dans une chaîne et signale qu’il est absent de la deuxième chaîne.

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

S’applique à