String.IndexOf String.IndexOf String.IndexOf String.IndexOf Method

Définition

Signale l'index de base zéro de la première occurrence d'un caractère ou d'une chaîne Unicode spécifiés dans cette instance.Reports the zero-based index of the first occurrence of a specified Unicode character or string within this instance. La méthode retourne -1 si le caractère ou la chaîne est introuvable dans cette instance.The method returns -1 if the character or string is not found in this instance.

Surcharges

IndexOf(String, Int32, Int32, StringComparison) IndexOf(String, Int32, Int32, StringComparison) IndexOf(String, Int32, Int32, StringComparison) IndexOf(String, Int32, Int32, StringComparison)

Signale l'index de base zéro de la première occurrence de la chaîne spécifiée dans l'objet String actuel.Reports the zero-based index of the first occurrence of the specified string in the current String object. Les paramètres spécifient le point de départ de la recherche dans la chaîne actuelle, le nombre de caractères de la chaîne dans laquelle effectuer la recherche et le type de recherche à utiliser pour la chaîne spécifiée.Parameters specify the starting search position in the current string, the number of characters in the current string to search, and the type of search to use for the specified string.

IndexOf(String, Int32, StringComparison) IndexOf(String, Int32, StringComparison) IndexOf(String, Int32, StringComparison) IndexOf(String, Int32, StringComparison)

Signale l'index de base zéro de la première occurrence de la chaîne spécifiée dans l'objet String actuel.Reports the zero-based index of the first occurrence of the specified string in the current String object. Les paramètres spécifient la position de départ de la recherche dans la chaîne actuelle et le type de recherche à utiliser pour la chaîne spécifiée.Parameters specify the starting search position in the current string and the type of search to use for the specified string.

IndexOf(Char, Int32, Int32) IndexOf(Char, Int32, Int32) IndexOf(Char, Int32, Int32) IndexOf(Char, Int32, Int32)

Signale l'index de base zéro de la première occurrence du caractère spécifié dans cette instance.Reports the zero-based index of the first occurrence of the specified character in this instance. La recherche commence à une position de caractère spécifiée et examine un nombre spécifié de positions de caractère.The search starts at a specified character position and examines a specified number of character positions.

IndexOf(String, StringComparison) IndexOf(String, StringComparison) IndexOf(String, StringComparison) IndexOf(String, StringComparison)

Signale l'index de base zéro de la première occurrence de la chaîne spécifiée dans l'objet String actuel.Reports the zero-based index of the first occurrence of the specified string in the current String object. Un paramètre spécifie le type de recherche à utiliser pour la chaîne spécifiée.A parameter specifies the type of search to use for the specified string.

IndexOf(String, Int32, Int32) IndexOf(String, Int32, Int32) IndexOf(String, Int32, Int32) IndexOf(String, Int32, Int32)

Signale l'index de base zéro de la première occurrence de la chaîne spécifiée dans cette instance.Reports the zero-based index of the first occurrence of the specified string in this instance. La recherche commence à une position de caractère spécifiée et examine un nombre spécifié de positions de caractère.The search starts at a specified character position and examines a specified number of character positions.

IndexOf(Char, StringComparison) IndexOf(Char, StringComparison) IndexOf(Char, StringComparison) IndexOf(Char, StringComparison)

Signale l'index de base zéro de la première occurrence du caractère Unicode spécifié dans cette chaîne.Reports the zero-based index of the first occurrence of the specified Unicode character in this string. Un paramètre spécifie le type de recherche à utiliser pour le caractère spécifié.A parameter specifies the type of search to use for the specified character.

IndexOf(Char, Int32) IndexOf(Char, Int32) IndexOf(Char, Int32) IndexOf(Char, Int32)

Signale l'index de base zéro de la première occurrence du caractère Unicode spécifié dans cette chaîne.Reports the zero-based index of the first occurrence of the specified Unicode character in this string. La recherche commence à une position de caractère spécifiée.The search starts at a specified character position.

IndexOf(String) IndexOf(String) IndexOf(String) IndexOf(String)

Signale l'index de base zéro de la première occurrence de la chaîne spécifiée dans cette instance.Reports the zero-based index of the first occurrence of the specified string in this instance.

IndexOf(Char) IndexOf(Char) IndexOf(Char) IndexOf(Char)

Signale l'index de base zéro de la première occurrence du caractère Unicode spécifié dans cette chaîne.Reports the zero-based index of the first occurrence of the specified Unicode character in this string.

IndexOf(String, Int32) IndexOf(String, Int32) IndexOf(String, Int32) IndexOf(String, Int32)

Signale l'index de base zéro de la première occurrence de la chaîne spécifiée dans cette instance.Reports the zero-based index of the first occurrence of the specified string in this instance. La recherche commence à une position de caractère spécifiée.The search starts at a specified character position.

IndexOf(String, Int32, Int32, StringComparison) IndexOf(String, Int32, Int32, StringComparison) IndexOf(String, Int32, Int32, StringComparison) IndexOf(String, Int32, Int32, StringComparison)

Signale l'index de base zéro de la première occurrence de la chaîne spécifiée dans l'objet String actuel.Reports the zero-based index of the first occurrence of the specified string in the current String object. Les paramètres spécifient le point de départ de la recherche dans la chaîne actuelle, le nombre de caractères de la chaîne dans laquelle effectuer la recherche et le type de recherche à utiliser pour la chaîne spécifiée.Parameters specify the starting search position in the current string, the number of characters in the current string to search, and the type of search to use for the specified string.

public:
 int IndexOf(System::String ^ value, int startIndex, int count, StringComparison comparisonType);
public int IndexOf (string value, int startIndex, int count, StringComparison comparisonType);
member this.IndexOf : string * int * int * StringComparison -> int
Public Function IndexOf (value As String, startIndex As Integer, count As Integer, comparisonType As StringComparison) As Integer

Paramètres

value
String String String String

Chaîne à rechercher.The string to seek.

startIndex
Int32 Int32 Int32 Int32

Position de départ de la recherche.The search starting position.

count
Int32 Int32 Int32 Int32

Nombre de positions de caractère à examiner.The number of character positions to examine.

comparisonType
StringComparison StringComparison StringComparison StringComparison

L'une des valeurs d'énumération qui spécifie les règles de la recherche.One of the enumeration values that specifies the rules for the search.

Retours

Position d’index de base zéro du paramètre value à partir du début de l’instance active si cette chaîne est trouvée, ou -1 si elle est introuvable.The zero-based index position of the value parameter from the start of the current instance if that string is found, or -1 if it is not. Si value est Empty, la valeur de retour est startIndex.If value is Empty, the return value is startIndex.

Exceptions

count ou startIndex est un nombre négatif.count or startIndex is negative.

ou-or- startIndex est supérieur à la longueur de cette instance.startIndex is greater than the length of this instance.

- ou --or- count est supérieur à la longueur de cette chaîne moins startIndex.count is greater than the length of this string minus startIndex.

comparisonType n’est pas une valeur de StringComparison valide.comparisonType is not a valid StringComparison value.

Exemples

L’exemple suivant illustre trois surcharges de la IndexOf méthode qui recherche la première occurrence d’une chaîne dans une autre chaîne à l’aide de différentes valeurs de la StringComparison énumération.The following example demonstrates three overloads of the IndexOf method that find the first occurrence of a string within another string using different values of the StringComparison enumeration.

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

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

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the first 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 StringComparison. Specify the start 
// index and count. 

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

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

// Search using different values of StringComparison. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(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 first 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.IndexOf(String, ..., StringComparison) methods.

Imports System
Imports System.Threading
Imports System.Globalization

Class Sample
    Public Shared Sub Main() 
        Dim intro As String = "Find the first 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 StringComparison. Specify the start 
        ' index and count.

        Console.WriteLine("Part 1: Start index and count are specified.")
        For Each sc In  scValues
            loc = cat.IndexOf(CapitalAWithRing, 0, cat.Length, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparison. Specify the 
        ' start index. 

        Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
        For Each sc In  scValues
            loc = cat.IndexOf(CapitalAWithRing, 0, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparison. 

        Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
        For Each sc In  scValues
            loc = cat.IndexOf(CapitalAWithRing, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
    
    End Sub 'Main
End Class 'Sample

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

Index numérotation commence à 0 (zéro).Index numbering starts from 0 (zero). Le paramètre startIndex peut varier entre 0 et la longueur de l'instance de chaîne.The startIndex parameter can range from 0 to the length of the string instance.

La recherche commence à startIndex et continue à startIndex + count -1.The search begins at startIndex and continues to startIndex + count -1. Le caractère situé à startIndex + count n’est pas inclus dans la recherche.The character at startIndex + count is not included in the search.

Le comparisonType paramètre permet de rechercher le value paramètre à l’aide de la culture actuelle ou indifférente, à l’aide d’une recherche de la casse et à l’aide des règles de comparaison ordinale ou de word.The comparisonType parameter specifies to search for the value parameter using the current or invariant culture, using a case-sensitive or case-insensitive search, and using word or ordinal comparison rules.

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.Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. 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é.In a culture-sensitive search (that is, if comparisonType is not Ordinal or OrdinalIgnoreCase), if value contains an ignorable character, the result is equivalent to searching with that character removed. Si value se compose uniquement d’un ou plusieurs caractères ignorables, le IndexOf(String, Int32, Int32, StringComparison) méthode retourne toujours startIndex, qui est la position de caractère à partir duquel commence la recherche.If value consists only of one or more ignorable characters, the IndexOf(String, Int32, Int32, StringComparison) method always returns startIndex, which is the character position at which the search begins.

Dans l’exemple suivant, la IndexOf(String, Int32, Int32, StringComparison) méthode est utilisée pour rechercher la position d’un trait d’union conditionnel (U + 00AD) suivie d’un « m » à partir de la troisième à la sixième position de caractère dans les deux chaînes.In the following example, the IndexOf(String, Int32, Int32, StringComparison) method is used to find the position of a soft hyphen (U+00AD) followed by an "m" starting in the third through sixth character positions in two strings. Une seule des chaînes contient la sous-chaîne requise.Only one of the strings contains the required substring. Si l’exemple est exécuté le .NET Framework 4.NET Framework 4 ou une version ultérieure, dans les deux cas, étant donné que le trait d’union conditionnel est un caractère ignorable, la méthode retourne l’index « m » dans la chaîne lorsqu’elle effectue une comparaison dépendante de la culture.If the example is run on the .NET Framework 4.NET Framework 4 or later, in both cases, because the soft hyphen is an ignorable character, the method returns the index of "m" in the string when it performs a culture-sensitive comparison. Lorsqu’elle effectue une comparaison ordinale, toutefois, il recherche la sous-chaîne uniquement dans la première chaîne.When it performs an ordinal comparison, however, it finds the substring only in the first string. Notez que dans le cas de la première chaîne, ce qui inclut le trait d’union conditionnel suivi d’un « m », la méthode ne parvient pas à retourner l’index du trait d’union, mais au lieu de cela retourne l’index du « m » lorsqu’il effectue une comparaison dépendante de la culture.Note that in the case of the first string, which includes the soft hyphen followed by an "m", the method fails to return the index of the soft hyphen but instead returns the index of the "m" when it performs a culture-sensitive comparison. La méthode retourne l'index du trait d'union conditionnel dans la première chaîne uniquement lorsqu'elle effectue une comparaison ordinale.The method returns the index of the soft hyphen in the first string only when it performs an ordinal comparison.

[!code-csharpSystem.String.IndexOf#24] [!code-vbSystem.String.IndexOf#24][!code-csharpSystem.String.IndexOf#24] [!code-vbSystem.String.IndexOf#24]

IndexOf(String, Int32, StringComparison) IndexOf(String, Int32, StringComparison) IndexOf(String, Int32, StringComparison) IndexOf(String, Int32, StringComparison)

Signale l'index de base zéro de la première occurrence de la chaîne spécifiée dans l'objet String actuel.Reports the zero-based index of the first occurrence of the specified string in the current String object. Les paramètres spécifient la position de départ de la recherche dans la chaîne actuelle et le type de recherche à utiliser pour la chaîne spécifiée.Parameters specify the starting search position in the current string and the type of search to use for the specified string.

public:
 int IndexOf(System::String ^ value, int startIndex, StringComparison comparisonType);
public int IndexOf (string value, int startIndex, StringComparison comparisonType);
member this.IndexOf : string * int * StringComparison -> int
Public Function IndexOf (value As String, startIndex As Integer, comparisonType As StringComparison) As Integer

Paramètres

value
String String String String

Chaîne à rechercher.The string to seek.

startIndex
Int32 Int32 Int32 Int32

Position de départ de la recherche.The search starting position.

comparisonType
StringComparison StringComparison StringComparison StringComparison

L'une des valeurs d'énumération qui spécifie les règles de la recherche.One of the enumeration values that specifies the rules for the search.

Retours

Position d’index de base zéro du paramètre value à partir du début de l’instance active si cette chaîne est trouvée, ou -1 si elle est introuvable.The zero-based index position of the value parameter from the start of the current instance if that string is found, or -1 if it is not. Si value est Empty, la valeur de retour est startIndex.If value is Empty, the return value is startIndex.

Exceptions

startIndex est inférieur à 0 (zéro) ou supérieur à la longueur de cette chaîne.startIndex is less than 0 (zero) or greater than the length of this string.

comparisonType n’est pas une valeur de StringComparison valide.comparisonType is not a valid StringComparison value.

Exemples

L’exemple suivant illustre trois surcharges de la IndexOf méthode qui recherche la première occurrence d’une chaîne dans une autre chaîne à l’aide de différentes valeurs de la StringComparison énumération.The following example demonstrates three overloads of the IndexOf method that find the first occurrence of a string within another string using different values of the StringComparison enumeration.

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

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

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the first 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 StringComparison. Specify the start 
// index and count. 

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

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

// Search using different values of StringComparison. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(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 first 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.IndexOf(String, ..., StringComparison) methods.

Imports System
Imports System.Threading
Imports System.Globalization

Class Sample
    Public Shared Sub Main() 
        Dim intro As String = "Find the first 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 StringComparison. Specify the start 
        ' index and count.

        Console.WriteLine("Part 1: Start index and count are specified.")
        For Each sc In  scValues
            loc = cat.IndexOf(CapitalAWithRing, 0, cat.Length, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparison. Specify the 
        ' start index. 

        Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
        For Each sc In  scValues
            loc = cat.IndexOf(CapitalAWithRing, 0, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparison. 

        Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
        For Each sc In  scValues
            loc = cat.IndexOf(CapitalAWithRing, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
    
    End Sub 'Main
End Class 'Sample

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

Numérotation de l’index commence à 0.Index numbering starts from 0. Le paramètre startIndex peut varier entre 0 et la longueur de l'instance de chaîne.The startIndex parameter can range from 0 to the length of the string instance. Si startIndex est égal à la longueur de l’instance de chaîne, la méthode retourne -1.If startIndex equals the length of the string instance, the method returns -1.

Le comparisonType paramètre permet de rechercher le value paramètre à l’aide de la culture actuelle ou indifférente, à l’aide d’une recherche de la casse et à l’aide des règles de comparaison ordinale ou de word.The comparisonType parameter specifies to search for the value parameter using the current or invariant culture, using a case-sensitive or case-insensitive search, and using word or ordinal comparison rules.

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.Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. 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é.In a culture-sensitive search (that is, if comparisonType is not Ordinal or OrdinalIgnoreCase), if value contains an ignorable character, the result is equivalent to searching with that character removed. Si value se compose uniquement d’un ou plusieurs caractères ignorables, le IndexOf(String, Int32, StringComparison) méthode retourne toujours startIndex, qui est la position de caractère à partir duquel commence la recherche.If value consists only of one or more ignorable characters, the IndexOf(String, Int32, StringComparison) method always returns startIndex, which is the character position at which the search begins.

Dans l’exemple suivant, la IndexOf(String, Int32, StringComparison) méthode est utilisée pour rechercher la position d’un trait d’union conditionnel (U + 00AD) suivie d’un « m » en commençant par la troisième position de caractère dans les deux chaînes.In the following example, the IndexOf(String, Int32, StringComparison) method is used to find the position of a soft hyphen (U+00AD) followed by an "m" starting with the third character position in two strings. Une seule des chaînes contient la sous-chaîne requise. Si l’exemple est exécuté le .NET Framework 4.NET Framework 4 ou une version ultérieure, dans les deux cas, étant donné que le trait d’union conditionnel est un caractère ignorable, la méthode retourne l’index « m » dans la chaîne lorsqu’elle effectue une comparaison dépendante de la culture.Only one of the strings contains the required substring.If the example is run on the .NET Framework 4.NET Framework 4 or later, in both cases, because the soft hyphen is an ignorable character, the method returns the index of "m" in the string when it performs a culture-sensitive comparison. Notez que, dans le cas de la première chaîne, qui inclut le trait d'union conditionnel suivi d'un « m », la méthode ne parvient pas à retourner l'index du trait d'union, mais retourne à la place celui de la lettre « m ».Note that in the case of the first string, which includes the soft hyphen followed by an "m", the method fails to return the index of the soft hyphen but instead returns the index of the "m". La méthode retourne l'index du trait d'union conditionnel dans la première chaîne uniquement lorsqu'elle effectue une comparaison ordinale.The method returns the index of the soft hyphen in the first string only when it performs an ordinal comparison.

[!code-csharpSystem.String.IndexOf#25] [!code-vbSystem.String.IndexOf#25][!code-csharpSystem.String.IndexOf#25] [!code-vbSystem.String.IndexOf#25]

IndexOf(Char, Int32, Int32) IndexOf(Char, Int32, Int32) IndexOf(Char, Int32, Int32) IndexOf(Char, Int32, Int32)

Signale l'index de base zéro de la première occurrence du caractère spécifié dans cette instance.Reports the zero-based index of the first occurrence of the specified character in this instance. La recherche commence à une position de caractère spécifiée et examine un nombre spécifié de positions de caractère.The search starts at a specified character position and examines a specified number of character positions.

public:
 int IndexOf(char value, int startIndex, int count);
public int IndexOf (char value, int startIndex, int count);
member this.IndexOf : char * int * int -> int
Public Function IndexOf (value As Char, startIndex As Integer, count As Integer) As Integer

Paramètres

value
Char Char Char Char

Caractère Unicode à rechercher.A Unicode character to seek.

startIndex
Int32 Int32 Int32 Int32

Position de départ de la recherche.The search starting position.

count
Int32 Int32 Int32 Int32

Nombre de positions de caractère à examiner.The number of character positions to examine.

Retours

Position d’index de base zéro de value à partir du début de la chaîne si ce caractère est trouvé, ou -1 s’il est introuvable.The zero-based index position of value from the start of the string if that character is found, or -1 if it is not.

Exceptions

count ou startIndex est un nombre négatif.count or startIndex is negative.

- ou --or- startIndex est supérieur à la longueur de cette chaîne.startIndex is greater than the length of this string.

- ou --or- count est supérieur à la longueur de cette chaîne moins startIndex.count is greater than the length of this string minus startIndex.

Exemples

L’exemple suivant montre le IndexOf (méthode).The following example demonstrates the IndexOf method.

// Example for the String::IndexOf( Char, int, int ) method.
using namespace System;
void FindAllChar( Char target, String^ searched )
{
   Console::Write( "The character '{0}' occurs at position(s): ", target );
   int startIndex = -1;
   int hitCount = 0;
   
   // Search for all occurrences of the target.
   while ( true )
   {
      startIndex = searched->IndexOf( target, startIndex + 1, searched->Length - startIndex - 1 );
      
      // Exit the loop if the target is not found.
      if ( startIndex < 0 )
            break;

      Console::Write( "{0}, ", startIndex );
      hitCount++;
   }

   Console::WriteLine( "occurrences: {0}", hitCount );
}

int main()
{
   String^ br1 = "0----+----1----+----2----+----3----+----"
   "4----+----5----+----6----+----7";
   String^ br2 = "0123456789012345678901234567890123456789"
   "0123456789012345678901234567890";
   String^ str = "ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi "
   "ABCDEFGHI abcdefghi ABCDEFGHI";
   Console::WriteLine( "This example of String::IndexOf( Char, int, int )\n"
   "generates the following output." );
   Console::WriteLine( "{0}{1}{0}{2}{0}{3}{0}", Environment::NewLine, br1, br2, str );
   FindAllChar( 'A', str );
   FindAllChar( 'a', str );
   FindAllChar( 'I', str );
   FindAllChar( 'i', str );
   FindAllChar( '@', str );
   FindAllChar( ' ', str );
}

/*
This example of String::IndexOf( Char, int, int )
generates the following output.

0----+----1----+----2----+----3----+----4----+----5----+----6----+----7
01234567890123456789012345678901234567890123456789012345678901234567890
ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI

The character 'A' occurs at position(s): 0, 20, 40, 60, occurrences: 4
The character 'a' occurs at position(s): 10, 30, 50, occurrences: 3
The character 'I' occurs at position(s): 8, 28, 48, 68, occurrences: 4
The character 'i' occurs at position(s): 18, 38, 58, occurrences: 3
The character '@' occurs at position(s): occurrences: 0
The character ' ' occurs at position(s): 9, 19, 29, 39, 49, 59, occurrences: 6
*/
// Example for the String.IndexOf( char, int, int ) method.
using System;

class IndexOfCII 
{
    public static void Main() 
    {
        string br1 = 
            "0----+----1----+----2----+----3----+----" +
            "4----+----5----+----6----+----7";
        string br2 = 
            "0123456789012345678901234567890123456789" +
            "0123456789012345678901234567890";
        string str = 
            "ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi " +
            "ABCDEFGHI abcdefghi ABCDEFGHI";

        Console.WriteLine( 
            "This example of String.IndexOf( char, int, int )\n" +
            "generates the following output." );
        Console.WriteLine( 
            "{0}{1}{0}{2}{0}{3}{0}", 
            Environment.NewLine, br1, br2, str );

        FindAllChar( 'A', str );
        FindAllChar( 'a', str );
        FindAllChar( 'I', str );
        FindAllChar( 'i', str );
        FindAllChar( '@', str );
        FindAllChar( ' ', str );
    }

    static void FindAllChar( Char target, String searched )
    {
        Console.Write( 
            "The character '{0}' occurs at position(s): ", 
            target );

        int     startIndex = -1;
        int     hitCount = 0;

        // Search for all occurrences of the target.
        while( true )
        {
            startIndex = searched.IndexOf( 
                target, startIndex + 1, 
                searched.Length - startIndex - 1 );

            // Exit the loop if the target is not found.
            if( startIndex < 0 )
                break;

            Console.Write( "{0}, ", startIndex );
            hitCount++;
        }

        Console.WriteLine( "occurrences: {0}", hitCount );
    }
}

/*
This example of String.IndexOf( char, int, int )
generates the following output.

0----+----1----+----2----+----3----+----4----+----5----+----6----+----7
01234567890123456789012345678901234567890123456789012345678901234567890
ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI

The character 'A' occurs at position(s): 0, 20, 40, 60, occurrences: 4
The character 'a' occurs at position(s): 10, 30, 50, occurrences: 3
The character 'I' occurs at position(s): 8, 28, 48, 68, occurrences: 4
The character 'i' occurs at position(s): 18, 38, 58, occurrences: 3
The character '@' occurs at position(s): occurrences: 0
The character ' ' occurs at position(s): 9, 19, 29, 39, 49, 59, occurrences: 6
*/
' Example for the String.IndexOf( Char, Integer, Integer ) method.
Imports System
Imports Microsoft.VisualBasic

Module IndexOfCII
   
    Sub Main()
        Dim br1 As String = _
            "0----+----1----+----2----+----3----+----" & _
            "4----+----5----+----6----+----7"
        Dim br2 As String = _
            "0123456789012345678901234567890123456789" & _
            "0123456789012345678901234567890"
        Dim str As String = _
            "ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi " & _
            "ABCDEFGHI abcdefghi ABCDEFGHI"
          
        Console.WriteLine( _
            "This example of String.IndexOf( Char, Integer, Integer )" & _
            vbCrLf & "generates the following output." )
        Console.WriteLine( _
            "{0}{1}{0}{2}{0}{3}{0}", _
            Environment.NewLine, br1, br2, str)

        FindAllChar("A"c, str)
        FindAllChar("a"c, str)
        FindAllChar("I"c, str)
        FindAllChar("i"c, str)
        FindAllChar("@"c, str)
        FindAllChar(" "c, str)
    End Sub 'Main
       
    Sub FindAllChar(target As Char, searched As String)

        Console.Write( _
            "The character ""{0}"" occurs at position(s): ", target)
          
        Dim startIndex As Integer = - 1
        Dim hitCount As Integer = 0
          
        ' Search for all occurrences of the target.
        While True
            startIndex = searched.IndexOf( _
                target, startIndex + 1, _
                searched.Length - startIndex - 1)

            ' Exit the loop if the target is not found.
            If startIndex < 0 Then
                Exit While
            End If 

            Console.Write("{0}, ", startIndex)
            hitCount += 1
        End While
          
        Console.WriteLine("occurrences: {0}", hitCount)

    End Sub 'FindAllChar
End Module 'IndexOfCII

' This example of String.IndexOf( Char, Integer, Integer )
' generates the following output.
' 
' 0----+----1----+----2----+----3----+----4----+----5----+----6----+----7
' 01234567890123456789012345678901234567890123456789012345678901234567890
' ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI
' 
' The character "A" occurs at position(s): 0, 20, 40, 60, occurrences: 4
' The character "a" occurs at position(s): 10, 30, 50, occurrences: 3
' The character "I" occurs at position(s): 8, 28, 48, 68, occurrences: 4
' The character "i" occurs at position(s): 18, 38, 58, occurrences: 3
' The character "@" occurs at position(s): occurrences: 0
' The character " " occurs at position(s): 9, 19, 29, 39, 49, 59, occurrences: 6

Remarques

La recherche commence à startIndex et continue à startIndex + count -1.The search begins at startIndex and continues to startIndex + count -1. Le caractère situé à startIndex + count n’est pas inclus dans la recherche.The character at startIndex + count is not included in the search.

Index numérotation commence à 0 (zéro).Index numbering starts from 0 (zero). Le paramètre startIndex peut varier entre 0 et la longueur de l'instance de chaîne.The startIndex parameter can range from 0 to the length of the string instance.

Cette méthode effectue une recherche ordinale (indépendante de la culture), où un caractère est considéré comme équivalent à un autre caractère uniquement si leurs valeurs Unicode sont identiques.This method performs an ordinal (culture-insensitive) search, where a character is considered equivalent to another character only if their Unicode scalar values are the same. Pour effectuer une recherche dépendante de la culture, utilisez la CompareInfo.IndexOf méthode, où une valeur scalaire Unicode représentant un caractère précomposé, telles que la ligature « Æ » (U + 00C 6), peut être considéré comme équivalent à n’importe quelle occurrence des composants du caractère dans la corriger la séquence, telles que « AE » (U + 0041, U + 0045), en fonction de la culture.To perform a culture-sensitive search, use the CompareInfo.IndexOf method, where a Unicode scalar value representing a precomposed character, such as the ligature "Æ" (U+00C6), might be considered equivalent to any occurrence of the character's components in the correct sequence, such as "AE" (U+0041, U+0045), depending on the culture.

Voir aussi

IndexOf(String, StringComparison) IndexOf(String, StringComparison) IndexOf(String, StringComparison) IndexOf(String, StringComparison)

Signale l'index de base zéro de la première occurrence de la chaîne spécifiée dans l'objet String actuel.Reports the zero-based index of the first occurrence of the specified string in the current String object. Un paramètre spécifie le type de recherche à utiliser pour la chaîne spécifiée.A parameter specifies the type of search to use for the specified string.

public:
 int IndexOf(System::String ^ value, StringComparison comparisonType);
public int IndexOf (string value, StringComparison comparisonType);
member this.IndexOf : string * StringComparison -> int
Public Function IndexOf (value As String, comparisonType As StringComparison) As Integer

Paramètres

value
String String String String

Chaîne à rechercher.The string to seek.

comparisonType
StringComparison StringComparison StringComparison StringComparison

L'une des valeurs d'énumération qui spécifie les règles de la recherche.One of the enumeration values that specifies the rules for the search.

Retours

Position d'index du paramètre value si cette chaîne est trouvée, sinon, -1.The index position of the value parameter if that string is found, or -1 if it is not. Si value est Empty, la valeur de retour est 0.If value is Empty, the return value is 0.

Exceptions

comparisonType n’est pas une valeur de StringComparison valide.comparisonType is not a valid StringComparison value.

Exemples

L’exemple suivant illustre trois surcharges de la IndexOf méthode qui recherche la première occurrence d’une chaîne dans une autre chaîne à l’aide de différentes valeurs de la StringComparison énumération.The following example demonstrates three overloads of the IndexOf method that find the first occurrence of a string within another string using different values of the StringComparison enumeration.

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

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

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the first 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 StringComparison. Specify the start 
// index and count. 

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

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

// Search using different values of StringComparison. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(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 first 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.IndexOf(String, ..., StringComparison) methods.

Imports System
Imports System.Threading
Imports System.Globalization

Class Sample
    Public Shared Sub Main() 
        Dim intro As String = "Find the first 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 StringComparison. Specify the start 
        ' index and count.

        Console.WriteLine("Part 1: Start index and count are specified.")
        For Each sc In  scValues
            loc = cat.IndexOf(CapitalAWithRing, 0, cat.Length, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparison. Specify the 
        ' start index. 

        Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
        For Each sc In  scValues
            loc = cat.IndexOf(CapitalAWithRing, 0, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
        
        ' Search using different values of StringComparison. 

        Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
        For Each sc In  scValues
            loc = cat.IndexOf(CapitalAWithRing, sc)
            Console.WriteLine(resultFmt, sc, loc)
        Next sc
    
    End Sub 'Main
End Class 'Sample

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

Numérotation de l’index commence à partir de zéro.Index numbering starts from zero.

Le comparisonType paramètre permet de rechercher le value paramètre à l’aide de la culture actuelle ou indifférente, à l’aide d’une recherche de la casse et à l’aide des règles de comparaison ordinale ou de word.The comparisonType parameter specifies to search for the value parameter using the current or invariant culture, using a case-sensitive or case-insensitive search, and using word or ordinal comparison rules.

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.Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. 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é.In a culture-sensitive search (that is, if comparisonType is not Ordinal or OrdinalIgnoreCase), if value contains an ignorable character, the result is equivalent to searching with that character removed. Si value se compose uniquement d’un ou plusieurs caractères ignorables, le IndexOf(String, StringComparison) méthode retourne toujours 0 (zéro) pour indiquer que la correspondance est trouvée au début de l’instance actuelle.If value consists only of one or more ignorable characters, the IndexOf(String, StringComparison) method always returns 0 (zero) to indicate that the match is found at the beginning of the current instance.

Dans l’exemple suivant, la IndexOf(String, StringComparison) méthode est utilisée pour rechercher des trois sous-chaînes (un trait d’union conditionnel (U + 00AD), un trait d’union conditionnel suivi par « n » et un trait d’union conditionnel suivi par « m ») dans les deux chaînes.In the following example, the IndexOf(String, StringComparison) method is used to find three substrings (a soft hyphen (U+00AD), a soft hyphen followed by "n", and a soft hyphen followed by "m") in two strings. Une seule des chaînes contient un trait d'union conditionnel.Only one of the strings contains a soft hyphen. Si l’exemple est exécuté le .NET Framework 4.NET Framework 4 ou une version ultérieure, étant donné que le trait d’union conditionnel est un caractère ignorable, une recherche dépendante de la culture retourne la même valeur que renverrait si le trait d’union conditionnel ne figuraient pas dans la chaîne de recherche.If the example is run on the .NET Framework 4.NET Framework 4 or later, because the soft hyphen is an ignorable character, a culture-sensitive search returns the same value that it would return if the soft hyphen were not included in the search string. Une recherche ordinale, toutefois, recherche le trait d’union conditionnel dans une chaîne avec succès et signale qu’il est absent de la deuxième chaîne.An ordinal search, however, successfully finds the soft hyphen in one string and reports that it is absent from the second string.

[!code-csharpSystem.String.IndexOf#26] [!code-vbSystem.String.IndexOf#26][!code-csharpSystem.String.IndexOf#26] [!code-vbSystem.String.IndexOf#26]

IndexOf(String, Int32, Int32) IndexOf(String, Int32, Int32) IndexOf(String, Int32, Int32) IndexOf(String, Int32, Int32)

Signale l'index de base zéro de la première occurrence de la chaîne spécifiée dans cette instance.Reports the zero-based index of the first occurrence of the specified string in this instance. La recherche commence à une position de caractère spécifiée et examine un nombre spécifié de positions de caractère.The search starts at a specified character position and examines a specified number of character positions.

public:
 int IndexOf(System::String ^ value, int startIndex, int count);
public int IndexOf (string value, int startIndex, int count);
member this.IndexOf : string * int * int -> int
Public Function IndexOf (value As String, startIndex As Integer, count As Integer) As Integer

Paramètres

value
String String String String

Chaîne à rechercher.The string to seek.

startIndex
Int32 Int32 Int32 Int32

Position de départ de la recherche.The search starting position.

count
Int32 Int32 Int32 Int32

Nombre de positions de caractère à examiner.The number of character positions to examine.

Retours

Position d’index de base zéro de value à partir du début de la instance actuelle si cette chaîne est trouvée, ou -1 si elle est introuvable.The zero-based index position of value from the start of the current instance if that string is found, or -1 if it is not. Si value est Empty, la valeur de retour est startIndex.If value is Empty, the return value is startIndex.

Exceptions

count ou startIndex est un nombre négatif.count or startIndex is negative.

- ou --or- startIndex est supérieur à la longueur de cette chaîne.startIndex is greater than the length of this string.

- ou --or- count est supérieur à la longueur de cette chaîne moins startIndex.count is greater than the length of this string minus startIndex.

Exemples

L’exemple suivant recherche l’index de toutes les occurrences de la chaîne « he » dans une sous-chaîne d’une autre chaîne.The following example finds the index of all occurrences of the string "he" within a substring of another string. Notez que le nombre de caractères à rechercher doit être recalculé, pour chaque itération de la recherche.Note that the number of characters to be searched must be recalculated for each search iteration.

// Sample for String::IndexOf(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 end;
   int count;
   end = str->Length;
   start = end / 2;
   Console::WriteLine();
   Console::WriteLine( "All occurrences of 'he' from position {0} to {1}.", start, end - 1 );
   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 <= end) && (at > -1) )
   {
      
      // start+count must be a position within -str-.
      count = end - start;
      at = str->IndexOf( "he", start, count );
      if ( at == -1 )
            break;

      Console::Write( "{0} ", at );
      start = at + 1;
   }

   Console::WriteLine();
}

/*
This example produces the following results:

All occurrences of 'he' from position 33 to 66.
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): 45 56

*/
// Sample for String.IndexOf(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 end;
    int count;

    end = str.Length;
    start = end/2;
    Console.WriteLine();
    Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, end-1);
    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 <= end) && (at > -1))
        {
// start+count must be a position within -str-.
        count = end - start;
        at = str.IndexOf("he", start, count);
        if (at == -1) break;
        Console.Write("{0} ", at);
        start = at+1;
        }
    Console.WriteLine();
    }
}
/*
This example produces the following results:

All occurrences of 'he' from position 33 to 66.
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): 45 56

*/
' Sample for String.IndexOf(String, Int32, 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
      Dim [end] As Integer
      Dim count As Integer
      
      [end] = str.Length
      start = [end] / 2
      Console.WriteLine()
      Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, [end] - 1)
      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 <= [end] AndAlso at > - 1
         ' start+count must be a position within -str-.
         count = [end] - start
         at = str.IndexOf("he", start, count)
         If at = - 1 Then
            Exit While
         End If
         Console.Write("{0} ", at)
         start = at + 1
      End While
      Console.WriteLine()
   End Sub 'Main
End Class 'Sample
'
'This example produces the following results:
'
'All occurrences of 'he' from position 33 to 66.
'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): 45 56
'
'

Remarques

Index numérotation commence à 0 (zéro).Index numbering starts from 0 (zero). Le paramètre startIndex peut varier entre 0 et la longueur de l'instance de chaîne.The startIndex parameter can range from 0 to the length of the string instance.

Cette méthode effectue une recherche de mots (respectant la casse et dépendante de la culture) à l’aide de la culture actuelle.This method performs a word (case-sensitive and culture-sensitive) search using the current culture. La recherche commence à startIndex et continue à startIndex + count -1.The search begins at startIndex and continues to startIndex + count -1. Le caractère situé à startIndex + count n’est pas inclus dans la recherche.The character at startIndex + count is not included in the search.

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.Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. 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é.In a culture-sensitive search, if value contains an ignorable character, the result is equivalent to searching with that character removed. Si value se compose uniquement d’un ou plusieurs caractères ignorables, le IndexOf(String, Int32, Int32) méthode retourne toujours startIndex, qui est la position de caractère à partir duquel commence la recherche.If value consists only of one or more ignorable characters, the IndexOf(String, Int32, Int32) method always returns startIndex, which is the character position at which the search begins. Dans l’exemple suivant, la IndexOf(String, Int32, Int32) méthode est utilisée pour rechercher la position d’un trait d’union conditionnel (U + 00AD) suivie d’un « m » à partir de la troisième à la sixième position de caractère dans les deux chaînes.In the following example, the IndexOf(String, Int32, Int32) method is used to find the position of a soft hyphen (U+00AD) followed by an "m" starting in the third through sixth character positions in two strings. Une seule des chaînes contient la sous-chaîne requise.Only one of the strings contains the required substring. Si l’exemple est exécuté le .NET Framework 4.NET Framework 4 ou une version ultérieure, dans les deux cas, étant donné que le trait d’union conditionnel est un caractère ignorable, la méthode retourne l’index « m » dans la chaîne lorsqu’elle effectue une comparaison dépendante de la culture.If the example is run on the .NET Framework 4.NET Framework 4 or later, in both cases, because the soft hyphen is an ignorable character, the method returns the index of "m" in the string when it performs a culture-sensitive comparison. Notez que, dans le cas de la première chaîne, qui inclut le trait d'union conditionnel suivi d'un « m », la méthode ne parvient pas à retourner l'index du trait d'union, mais retourne à la place celui de la lettre « m ».Note that in the case of the first string, which includes the soft hyphen followed by an "m", the method fails to return the index of the soft hyphen but instead returns the index of the "m".

using System;

public class Example
{
   public static void Main()
   {
      string searchString = "\u00ADm";
      string s1 = "ani\u00ADmal" ;
      string s2 = "animal";

      Console.WriteLine(s1.IndexOf(searchString, 2, 4));
      Console.WriteLine(s2.IndexOf(searchString, 2, 4));
   }
}
// The example displays the following output:
//       4
//       3
Module Example
   Public Sub Main()
      Dim searchString As String = Chrw(&h00AD) + "m"
      Dim s1 As String = "ani" + ChrW(&h00AD) + "mal"
      Dim s2 As String = "animal"

      Console.WriteLine(s1.IndexOf(searchString, 2, 4))
      Console.WriteLine(s2.IndexOf(searchString, 2, 4))
   End Sub
End Module
' The example displays the following output:
'       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 substituent des valeurs par défaut et à la place appellent des méthodes qui requièrent des paramètres explicitement spécifiés.As explained in Best Practices for Using Strings, we recommend that you avoid calling string comparison methods that substitute default values and instead call methods that require parameters to be explicitly specified. Pour utiliser les règles de comparaison de la culture actuelle pour effectuer cette opération, appelez le IndexOf(String, Int32, Int32, StringComparison) surcharge de méthode avec une valeur de CurrentCulture pour son comparisonType paramètre.To use the comparison rules of the current culture to perform this operation, call the IndexOf(String, Int32, Int32, StringComparison) method overload with a value of CurrentCulture for its comparisonType parameter.

Voir aussi

IndexOf(Char, StringComparison) IndexOf(Char, StringComparison) IndexOf(Char, StringComparison) IndexOf(Char, StringComparison)

Signale l'index de base zéro de la première occurrence du caractère Unicode spécifié dans cette chaîne.Reports the zero-based index of the first occurrence of the specified Unicode character in this string. Un paramètre spécifie le type de recherche à utiliser pour le caractère spécifié.A parameter specifies the type of search to use for the specified character.

public:
 int IndexOf(char value, StringComparison comparisonType);
public int IndexOf (char value, StringComparison comparisonType);
member this.IndexOf : char * StringComparison -> int
Public Function IndexOf (value As Char, comparisonType As StringComparison) As Integer

Paramètres

value
Char Char Char Char

Caractère à rechercher.The character to seek.

comparisonType
StringComparison StringComparison StringComparison StringComparison

Une valeur d’énumération qui spécifie les règles de la recherche.An enumeration value that specifies the rules for the search.

Retours

Index de base zéro de value si ce caractère est trouvé, ou -1 s’il est introuvable.The zero-based index of value if that character is found, or -1 if it is not.

Exceptions

comparisonType n’est pas une valeur de StringComparison valide.comparisonType is not a valid StringComparison value.

Remarques

Numérotation de l’index commence à partir de zéro.Index numbering starts from zero.

Le comparisonType paramètre est un StringComparison membre d’énumération qui spécifie si la recherche de la value argument utilise la culture actuelle ou invariante, est la casse ou word ou des règles de comparaison ordinale.The comparisonType parameter is a StringComparison enumeration member that specifies whether the search for the value argument uses the current or invariant culture, is case-sensitive or case-insensitive, or uses word or ordinal comparison rules.

IndexOf(Char, Int32) IndexOf(Char, Int32) IndexOf(Char, Int32) IndexOf(Char, Int32)

Signale l'index de base zéro de la première occurrence du caractère Unicode spécifié dans cette chaîne.Reports the zero-based index of the first occurrence of the specified Unicode character in this string. La recherche commence à une position de caractère spécifiée.The search starts at a specified character position.

public:
 int IndexOf(char value, int startIndex);
public int IndexOf (char value, int startIndex);
member this.IndexOf : char * int -> int
Public Function IndexOf (value As Char, startIndex As Integer) As Integer

Paramètres

value
Char Char Char Char

Caractère Unicode à rechercher.A Unicode character to seek.

startIndex
Int32 Int32 Int32 Int32

Position de départ de la recherche.The search starting position.

Retours

Position d’index de base zéro de value à partir du début de la chaîne si ce caractère est trouvé, ou -1 s’il est introuvable.The zero-based index position of value from the start of the string if that character is found, or -1 if it is not.

Exceptions

startIndex est inférieur à 0 (zéro) ou supérieur à la longueur de la chaîne.startIndex is less than 0 (zero) or greater than the length of the string.

Exemples

L’exemple suivant montre le IndexOf (méthode).The following example demonstrates the IndexOf method.

// Sample for String::IndexOf(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;
   Console::WriteLine();
   Console::WriteLine( "All occurrences of 't' from position 0 to {0}.", str->Length - 1 );
   Console::WriteLine( "{1}{0}{2}{0}{3}{0}", Environment::NewLine, br1, br2, str );
   Console::Write( "The letter 't' occurs at position(s): " );
   at = 0;
   start = 0;
   while ( (start < str->Length) && (at > -1) )
   {
      at = str->IndexOf( 't', start );
      if ( at == -1 )
            break;

      Console::Write( "{0} ", at );
      start = at + 1;
   }

   Console::WriteLine();
}

/*
This example produces the following results:

All occurrences of 't' from position 0 to 66.
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): 7 11 33 41 44 55 64

*/
// Sample for String.IndexOf(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;

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

    at = 0;
    start = 0; 
    while((start < str.Length) && (at > -1))
        {
        at = str.IndexOf('t', start);
        if (at == -1) break;
        Console.Write("{0} ", at);
        start = at+1;
        }
    Console.WriteLine();
    }
}
/*
This example produces the following results:

All occurrences of 't' from position 0 to 66.
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): 7 11 33 41 44 55 64

*/
' Sample for String.IndexOf(Char, Int32)

Module Sample
    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

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

        at = 0
        start = 0
        While start < str.Length AndAlso at > -1
            at = str.IndexOf("t"c, start)
            If at = -1 Then
                Exit While
            End If
            Console.Write("{0} ", at)
            start = at + 1
        End While
        Console.WriteLine()
    End Sub
End Module
'
'This example produces the following results:
'
'All occurrences of 't' from position 0 to 66.
'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): 7 11 33 41 44 55 64
'
'

Remarques

Numérotation de l’index commence à 0.Index numbering starts from 0. Le paramètre startIndex peut varier entre 0 et la longueur de l'instance de chaîne.The startIndex parameter can range from 0 to the length of the string instance. Si startIndex est égal à la longueur de l’instance de chaîne, la méthode retourne -1.If startIndex equals the length of the string instance, the method returns -1.

La recherche s’étend de startIndex à la fin de la chaîne.The search ranges from startIndex to the end of the string.

Cette méthode effectue une recherche ordinale (indépendante de la culture), où un caractère est considéré comme équivalent à un autre caractère uniquement si leurs valeurs Unicode sont identiques.This method performs an ordinal (culture-insensitive) search, where a character is considered equivalent to another character only if their Unicode scalar values are the same. Pour effectuer une recherche dépendante de la culture, utilisez la CompareInfo.IndexOf méthode, où une valeur scalaire Unicode représentant un caractère précomposé, telles que la ligature « Æ » (U + 00C 6), peut être considéré comme équivalent à n’importe quelle occurrence des composants du caractère dans la corriger la séquence, telles que « AE » (U + 0041, U + 0045), en fonction de la culture.To perform a culture-sensitive search, use the CompareInfo.IndexOf method, where a Unicode scalar value representing a precomposed character, such as the ligature "Æ" (U+00C6), might be considered equivalent to any occurrence of the character's components in the correct sequence, such as "AE" (U+0041, U+0045), depending on the culture.

Voir aussi

IndexOf(String) IndexOf(String) IndexOf(String) IndexOf(String)

Signale l'index de base zéro de la première occurrence de la chaîne spécifiée dans cette instance.Reports the zero-based index of the first occurrence of the specified string in this instance.

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

Paramètres

value
String String String String

Chaîne à rechercher.The string to seek.

Retours

Position d'index de base zéro de value si cette chaîne est disponible ou -1 si elle est introuvable.The zero-based index position of value if that string is found, or -1 if it is not. Si value est Empty, la valeur de retour est 0.If value is Empty, the return value is 0.

Exceptions

Exemples

L’exemple suivant recherche la valeur « n » dans « animal ».The following example searches for the "n" in "animal". Étant donné que les index de chaîne commencent à zéro au lieu, le IndexOf(String) méthode indique que le « n » est à la position 1.Because string indexes begin at zero rather than one, the IndexOf(String) method indicates that the "n" is at position 1.

using namespace System;

void main()
{
   String^ str = "animal";
   String^ toFind = "n";
   int index = str->IndexOf("n");
   Console::WriteLine("Found '{0}' in '{1}' at position {2}",
                        toFind, str, index);

}
// The example displays the following output:
//        Found 'n' in 'animal' at position 1
using System;

public class Example
{
   public static void Main()
   {
      String str = "animal";
      String toFind = "n";
      int index = str.IndexOf("n");
      Console.WriteLine("Found '{0}' in '{1}' at position {2}",
                        toFind, str, index);
   }
}
// The example displays the following output:
//        Found 'n' in 'animal' at position 1
Public Module Example
   Public Sub Main()
      Dim str As String = "animal"
      Dim toFind As String = "n"
      Dim index As Integer = str.IndexOf("n")
      Console.WriteLine("Found '{0}' in '{1}' at position {2}",
                        toFind, str, index)
   End Sub
End Module
' The example displays the following output:
'       Found 'n' in 'animal' at position 1

L’exemple suivant utilise la IndexOf méthode pour déterminer la position de départ d’un nom d’animal dans une phrase.The following example uses the IndexOf method to determine the starting position of an animal name in a sentence. Il utilise ensuite cette position pour insérer un adjectif qui décrit l’animal dans la phrase.It then uses this position to insert an adjective that describes the animal into the sentence.

using namespace System;

int main()
{
   String^ animal1 = "fox";
   String^ animal2 = "dog";
   String^ strTarget = String::Format( "The {0} jumps over the {1}.", animal1, animal2 );
   Console::WriteLine( "The original string is:{0}{1}{0}", Environment::NewLine, strTarget );
   Console::Write( "Enter an adjective (or group of adjectives) to describe the {0}: ==> ", animal1 );
   String^ adj1 = Console::ReadLine();
   Console::Write( "Enter an adjective (or group of adjectives) to describe the {0}: ==> ", animal2 );
   String^ adj2 = Console::ReadLine();
   adj1 = String::Concat( adj1->Trim(), " " );
   adj2 = String::Concat( adj2->Trim(), " " );
   strTarget = strTarget->Insert( strTarget->IndexOf( animal1 ), adj1 );
   strTarget = strTarget->Insert( strTarget->IndexOf( animal2 ), adj2 );
   Console::WriteLine( " {0}The final string is: {0} {1}", Environment::NewLine, strTarget );
}
// Output from the example might appear as follows:
//       The original string is:
//       The fox jumps over the dog.
//       
//       Enter an adjective (or group of adjectives) to describe the fox: ==> bold
//       Enter an adjective (or group of adjectives) to describe the dog: ==> lazy
//       
//       The final string is:
//       The bold fox jumps over the lazy dog.
using System;

public class Example {
    public static void Main() 
    {
        string animal1 = "fox";
        string animal2 = "dog";

        string strTarget = String.Format("The {0} jumps over the {1}.", 
                                         animal1, animal2);

        Console.WriteLine("The original string is:{0}{1}{0}", 
                          Environment.NewLine, strTarget);

        Console.Write("Enter an adjective (or group of adjectives) " +
                      "to describe the {0}: ==> ", animal1);
        string adj1 = Console.ReadLine();

        Console.Write("Enter an adjective (or group of adjectives) " + 
                      "to describe the {0}: ==> ", animal2);    
        string adj2 = Console.ReadLine();

        adj1 = adj1.Trim() + " ";
        adj2 = adj2.Trim() + " ";

        strTarget = strTarget.Insert(strTarget.IndexOf(animal1), adj1);
        strTarget = strTarget.Insert(strTarget.IndexOf(animal2), adj2);

        Console.WriteLine("{0}The final string is:{0}{1}", 
                          Environment.NewLine, strTarget);
    }
}
// Output from the example might appear as follows:
//       The original string is:
//       The fox jumps over the dog.
//       
//       Enter an adjective (or group of adjectives) to describe the fox: ==> bold
//       Enter an adjective (or group of adjectives) to describe the dog: ==> lazy
//       
//       The final string is:
//       The bold fox jumps over the lazy dog.
Public Class Example
    Public Shared Sub Main()
        Dim animal1 As String = "fox"
        Dim animal2 As String = "dog"
        Dim strTarget As String = String.Format("The {0} jumps over the {1}.", 
                                                animal1, animal2)
        
        Console.WriteLine("The original string is: {0}{1}{0}", 
                          Environment.NewLine, strTarget)
        
        Console.Write("Enter an adjective (or group of adjectives) " +
                      "to describe the {0}: ==> ", animal1)
        Dim adj1 As String = Console.ReadLine()
        
        Console.Write("Enter an adjective (or group of adjectives) " + 
                      "to describe the {0}: ==> ", animal2)
        Dim adj2 As String = Console.ReadLine()
        
        adj1 = adj1.Trim() + " "
        adj2 = adj2.Trim() + " "
        
        strTarget = strTarget.Insert(strTarget.IndexOf(animal1), adj1)
        strTarget = strTarget.Insert(strTarget.IndexOf(animal2), adj2)
        
        Console.WriteLine("{0}The final string is:{0}{1}", 
                          Environment.NewLine, strTarget)
    End Sub 
End Class 
' Output from the example might appear as follows:
'       The original string is:
'       The fox jumps over the dog.
'       
'       Enter an adjective (or group of adjectives) to describe the fox: ==> bold
'       Enter an adjective (or group of adjectives) to describe the dog: ==> lazy
'       
'       The final string is:
'       The bold fox jumps over the lazy dog.

Remarques

Numérotation de l’index commence à partir de zéro.Index numbering starts from zero.

Cette méthode effectue une recherche de mots (respectant la casse et dépendante de la culture) à l’aide de la culture actuelle.This method performs a word (case-sensitive and culture-sensitive) search using the current culture. La recherche commence à la première position de caractère de cette instance et continue jusqu'à la dernière position de caractère.The search begins at the first character position of this instance and continues until the last character position.

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.Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. 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é.In a culture-sensitive search, if value contains an ignorable character, the result is equivalent to searching with that character removed. Si value se compose uniquement d’un ou plusieurs caractères ignorables, le IndexOf(String) méthode retourne toujours 0 (zéro) pour indiquer que la correspondance est trouvée au début de l’instance actuelle.If value consists only of one or more ignorable characters, the IndexOf(String) method always returns 0 (zero) to indicate that the match is found at the beginning of the current instance. Dans l’exemple suivant, la IndexOf(String) méthode est utilisée pour rechercher des trois sous-chaînes (un trait d’union conditionnel (U + 00AD), un trait d’union conditionnel suivi par « n » et un trait d’union conditionnel suivi par « m ») dans les deux chaînes.In the following example, the IndexOf(String) method is used to find three substrings (a soft hyphen (U+00AD), a soft hyphen followed by "n", and a soft hyphen followed by "m") in two strings. Une seule des chaînes contient un trait d'union conditionnel.Only one of the strings contains a soft hyphen. Si l’exemple est exécuté le .NET Framework 4.NET Framework 4 ou version ultérieure, dans chaque cas, étant donné que le trait d’union conditionnel est un caractère ignorable, le résultat est le même comme si le trait d’union conditionnel n’avait pas été inclus dans value.If the example is run on the .NET Framework 4.NET Framework 4 or later, in each case, because the soft hyphen is an ignorable character, the result is the same as if the soft hyphen had not been included in value. Lorsque vous recherchez un trait d’union conditionnel uniquement, la méthode retourne 0 (zéro) pour indiquer qu’il a trouvé une correspondance au début de la chaîne.When searching for a soft hyphen only, the method returns 0 (zero) to indicate that it has found a match at the beginning of the string.

using System;

public class Example
{
   public static void Main()
   {
      string s1 = "ani\u00ADmal";
      string s2 = "animal";
      
      // Find the index of the soft hyphen.
      Console.WriteLine(s1.IndexOf("\u00AD"));
      Console.WriteLine(s2.IndexOf("\u00AD"));
      
      // Find the index of the soft hyphen followed by "n".
      Console.WriteLine(s1.IndexOf("\u00ADn"));
      Console.WriteLine(s2.IndexOf("\u00ADn"));
      
      // Find the index of the soft hyphen followed by "m".
      Console.WriteLine(s1.IndexOf("\u00ADm"));
      Console.WriteLine(s2.IndexOf("\u00ADm"));
   }
}
// The example displays the following output
// if run under the .NET Framework 4 or later:
//       0
//       0
//       1
//       1
//       4
//       3
Module Example
   Public Sub Main()
      Dim softHyphen As String = ChrW(&h00AD)
      Dim s1 As String = "ani" + softHyphen + "mal"
      Dim s2 As String = "animal"
      
      ' Find the index of the soft hyphen.
      Console.WriteLine(s1.IndexOf(softHyphen))
      Console.WriteLine(s2.IndexOf(softHyphen))
      
      ' Find the index of the soft hyphen followed by "n".
      Console.WriteLine(s1.IndexOf(softHyphen + "n"))
      Console.WriteLine(s2.IndexOf(softHyphen + "n"))
      
      ' Find the index of the soft hyphen followed by "m".
      Console.WriteLine(s1.IndexOf(softHyphen + "m"))
      Console.WriteLine(s2.IndexOf(softHyphen + "m"))
   End Sub
End Module
' The example displays the following output 
' if run under the .NET Framework 4 or later:
'       0
'       0
'       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 substituent des valeurs par défaut et à la place appellent des méthodes qui requièrent des paramètres explicitement spécifiés.As explained in Best Practices for Using Strings, we recommend that you avoid calling string comparison methods that substitute default values and instead call methods that require parameters to be explicitly specified. Pour rechercher le premier index d’une sous-chaîne dans une instance de chaîne en utilisant les règles de comparaison de la culture actuelle, appelez le IndexOf(String, StringComparison) surcharge de méthode avec une valeur de CurrentCulture pour son comparisonType paramètre.To find the first index of a substring within a string instance by using the comparison rules of the current culture, call the IndexOf(String, StringComparison) method overload with a value of CurrentCulture for its comparisonType parameter.

Voir aussi

IndexOf(Char) IndexOf(Char) IndexOf(Char) IndexOf(Char)

Signale l'index de base zéro de la première occurrence du caractère Unicode spécifié dans cette chaîne.Reports the zero-based index of the first occurrence of the specified Unicode character in this string.

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

Paramètres

value
Char Char Char Char

Caractère Unicode à rechercher.A Unicode character to seek.

Retours

Position d'index de base zéro de value si ce caractère est disponible ou -1 s'il est introuvable.The zero-based index position of value if that character is found, or -1 if it is not.

Exemples

L’exemple suivant montre comment vous pouvez rechercher un String d’un caractère en utilisant la IndexOf (méthode).The following example demonstrates how you can search a String for a character using the IndexOf method.

using namespace System;

void main()
{
   // Create a Unicode String with 5 Greek Alpha characters.
   String^ szGreekAlpha = gcnew String(L'\x0391',5);

   // Create a Unicode String with a 3 Greek Omega characters.
   String^ szGreekOmega = L"\x03A9\x03A9\x03A9";

   String^ szGreekLetters = String::Concat(szGreekOmega, szGreekAlpha, 
                                           szGreekOmega->Clone());

   // Display the entire string.
   Console::WriteLine(szGreekLetters);

   // The first index of Alpha.
   int ialpha = szGreekLetters->IndexOf( L'\x0391');
   // The first index of Omega.
   int iomega = szGreekLetters->IndexOf(L'\x03A9');

   Console::WriteLine("First occurrence of the Greek letter Alpha: Index {0}", 
                      ialpha);
   Console::WriteLine("First occurrence of the Greek letter Omega: Index {0}", 
                      iomega);
}
// The example displays the following output:
//       The string: OOO?????OOO
//       First occurrence of the Greek letter Alpha: Index 3
//       First occurrence of the Greek letter Omega: Index 0
using System;

class Example
{
   static void Main()
   {
      // Create a Unicode string with 5 Greek Alpha characters.
      String szGreekAlpha = new String('\u0391',5);

      // Create a Unicode string with 3 Greek Omega characters.
      String szGreekOmega = "\u03A9\u03A9\u03A9";
      
      String szGreekLetters = String.Concat(szGreekOmega, szGreekAlpha, 
                                            szGreekOmega.Clone());

      // Display the entire string.
      Console.WriteLine("The string: {0}", szGreekLetters);

      // The first index of Alpha.
      int ialpha = szGreekLetters.IndexOf('\u0391');
      // The first index of Omega.
      int iomega = szGreekLetters.IndexOf('\u03A9');

      Console.WriteLine("First occurrence of the Greek letter Alpha: Index {0}", 
                        ialpha);
      Console.WriteLine("First occurrence of the Greek letter Omega: Index {0}", 
                        iomega);
   }
} 
// The example displays the following output:
//    The string: OOO?????OOO
//    First occurrence of the Greek letter Alpha: Index 3
//    First occurrence of the Greek letter Omega: Index 0
Public Module Example
   Public Sub Main()
      ' Create a Unicode string with 5 Greek Alpha characters.
      Dim szGreekAlpha As New String(ChrW(&H0391), 5)

      ' Create a Unicode string with 3 Greek Omega characters.
      Dim szGreekOmega As String = ChrW(&H03A9) + ChrW(&H03A9)+
                                   ChrW(&H03A9)

      Dim szGreekLetters As String = String.Concat(szGreekOmega, szGreekAlpha, _
                                                   szGreekOmega.Clone())

      ' Display the entire string.
      Console.WriteLine(szGreekLetters)

      ' The first index of Alpha.
      Dim iAlpha As Integer = szGreekLetters.IndexOf(ChrW(&H0391))
      ' The first index of Omega.
      Dim iomega As Integer = szGreekLetters.IndexOf(ChrW(&H03A9))

      Console.WriteLine("First occurrence of the Greek letter Alpha: Index {0}", 
                        ialpha)
      Console.WriteLine("First occurrence of the Greek letter Omega: Index {0}", 
                        iomega)
   End Sub
End Module
' The example displays the following output:
'       The string: OOO?????OOO
'       First occurrence of the Greek letter Alpha: Index 3
'       First occurrence of the Greek letter Omega: Index 0

Remarques

Numérotation de l’index commence à partir de zéro.Index numbering starts from zero.

Cette méthode effectue une recherche ordinale (indépendante de la culture), où un caractère est considéré comme équivalent à un autre caractère uniquement si leurs valeurs Unicode sont identiques.This method performs an ordinal (culture-insensitive) search, where a character is considered equivalent to another character only if their Unicode scalar values are the same. Pour effectuer une recherche dépendante de la culture, utilisez la CompareInfo.IndexOf méthode, où une valeur scalaire Unicode représentant un caractère précomposé, telles que la ligature « Æ » (U + 00C 6), peut être considéré comme équivalent à n’importe quelle occurrence des composants du caractère dans la corriger la séquence, telles que « AE » (U + 0041, U + 0045), en fonction de la culture.To perform a culture-sensitive search, use the CompareInfo.IndexOf method, where a Unicode scalar value representing a precomposed character, such as the ligature "Æ" (U+00C6), might be considered equivalent to any occurrence of the character's components in the correct sequence, such as "AE" (U+0041, U+0045), depending on the culture.

Voir aussi

IndexOf(String, Int32) IndexOf(String, Int32) IndexOf(String, Int32) IndexOf(String, Int32)

Signale l'index de base zéro de la première occurrence de la chaîne spécifiée dans cette instance.Reports the zero-based index of the first occurrence of the specified string in this instance. La recherche commence à une position de caractère spécifiée.The search starts at a specified character position.

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

Paramètres

value
String String String String

Chaîne à rechercher.The string to seek.

startIndex
Int32 Int32 Int32 Int32

Position de départ de la recherche.The search starting position.

Retours

Position d’index de base zéro de value à partir du début de la instance actuelle si cette chaîne est trouvée, ou -1 si elle est introuvable.The zero-based index position of value from the start of the current instance if that string is found, or -1 if it is not. Si value est Empty, la valeur de retour est startIndex.If value is Empty, the return value is startIndex.

Exceptions

startIndex est inférieur à 0 (zéro) ou supérieur à la longueur de cette chaîne.startIndex is less than 0 (zero) or greater than the length of this string.

Exemples

L’exemple suivant recherche toutes les occurrences d’une chaîne spécifiée dans une chaîne cible.The following example searches for all occurrences of a specified string within a target string.

using namespace System;
int main()
{
   String^ strSource = "This is the string which we will perform the search on";
   Console::WriteLine( "The search string is: {0}\"{1}\" {0}", Environment::NewLine, strSource );
   String^ strTarget = "";
   int found = 0;
   int totFinds = 0;
   do
   {
      Console::Write( "Please enter a search value to look for in the above string (hit Enter to exit) ==> " );
      strTarget = Console::ReadLine();
      if (  !strTarget->Equals( "" ) )
      {
         for ( int i = 0; i < strSource->Length; i++ )
         {
            found = strSource->IndexOf( strTarget, i );
            if (found >= 0)
            {
               totFinds++;
               i = found;
            }
            else
               break;

         }
      }
      else
            return 0;
      Console::WriteLine( "{0}The search parameter '{1}' was found {2} times. {0}", Environment::NewLine, strTarget, totFinds );
      totFinds = 0;
   }
   while ( true );
}

using System;

public class IndexOfTest {
    public static void Main() {

        string strSource = "This is the string which we will perform the search on";

        Console.WriteLine("The search string is:{0}\"{1}\"{0}", Environment.NewLine, strSource);

        string strTarget = "";
        int found = 0;
        int totFinds = 0;

        do {
            Console.Write("Please enter a search value to look for in the above string (hit Enter to exit) ==> ");

            strTarget = Console.ReadLine();

            if (strTarget != "") {

                for (int i = 0; i < strSource.Length; i++) {

                    found = strSource.IndexOf(strTarget, i);

                    if (found >= 0) {
                        totFinds++;
                        i = found;
                    }
                    else
                        break;
                }
            }
            else
                return;

            Console.WriteLine("{0}The search parameter '{1}' was found {2} times.{0}",
                    Environment.NewLine, strTarget, totFinds);

            totFinds = 0;

        } while ( true );
    }
}
Imports System

Public Class IndexOfTest
    
    Public Shared Sub Main()
        Dim strSource As String = "This is the string which we will perform the search on"
        
        Console.WriteLine("The search string is:{0}{1}{0}", Environment.NewLine, strSource)
        Dim strTarget As String = ""
        Dim found As Integer = 0
        Dim totFinds As Integer = 0
        
        Do
            Console.Write("Please enter a search value to look for in the above string (hit Enter to exit) ==> ")
            
            strTarget = Console.ReadLine()
            If strTarget <> "" Then
                Dim i As Integer
                
                
                For i = 0 To strSource.Length - 1
                    
                    found = strSource.IndexOf(strTarget, i)
                    If found >= 0 Then
                        
                        totFinds += 1
                        i = found
                    Else
                        Exit For
                    End If
                Next i
            Else
                Return
            
            End If
            Console.WriteLine("{0}The search parameter '{1}' was found {2} times.{0}", Environment.NewLine, strTarget, totFinds)
            
            totFinds = 0
        
        Loop While True
    End Sub 'Main
End Class 'IndexOfTest

Remarques

Numérotation de l’index commence à 0.Index numbering starts from 0. Le paramètre startIndex peut varier entre 0 et la longueur de l'instance de chaîne.The startIndex parameter can range from 0 to the length of the string instance. Si startIndex est égal à la longueur de l’instance de chaîne, la méthode retourne -1.If startIndex equals the length of the string instance, the method returns -1.

Cette méthode effectue une recherche de mots (respectant la casse et dépendante de la culture) à l’aide de la culture actuelle.This method performs a word (case-sensitive and culture-sensitive) search using the current culture. La recherche commence à la startIndex position de cette instance de caractère et continue jusqu'à la dernière position de caractère.The search begins at the startIndex character position of this instance and continues until the last character position.

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.Character sets include ignorable characters, which are characters that are not considered when performing a linguistic or culture-sensitive comparison. 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é.In a culture-sensitive search, if value contains an ignorable character, the result is equivalent to searching with that character removed. Si value se compose uniquement d’un ou plusieurs caractères ignorables, le IndexOf(String, Int32) méthode retourne toujours startIndex, qui est la position de caractère à partir duquel commence la recherche.If value consists only of one or more ignorable characters, the IndexOf(String, Int32) method always returns startIndex, which is the character position at which the search begins. Dans l’exemple suivant, la IndexOf(String, Int32) méthode est utilisée pour rechercher la position d’un trait d’union conditionnel (U + 00AD) suivie d’un « m » dans les deux chaînes.In the following example, the IndexOf(String, Int32) method is used to find the position of a soft hyphen (U+00AD) followed by an "m" in two strings. Une seule des chaînes contient la sous-chaîne requise.Only one of the strings contains the required substring. Si l’exemple est exécuté le .NET Framework 4.NET Framework 4 ou une version ultérieure, dans les deux cas, étant donné que le trait d’union conditionnel est un caractère ignorable, la méthode retourne l’index « m » dans la chaîne.If the example is run on the .NET Framework 4.NET Framework 4 or later, in both cases, because the soft hyphen is an ignorable character, the method returns the index of "m" in the string. Notez que, dans le cas de la première chaîne, qui inclut le trait d'union conditionnel suivi d'un « m », la méthode ne parvient pas à retourner l'index du trait d'union, mais retourne à la place celui de la lettre « m ».Note that in the case of the first string, which includes the soft hyphen followed by an "m", the method fails to return the index of the soft hyphen but instead returns the index of the "m".

using System;

public class Example
{
   public static void Main()
   {
      string searchString = "\u00ADm";
      string s1 = "ani\u00ADmal" ;
      string s2 = "animal";

      Console.WriteLine(s1.IndexOf(searchString, 2));
      Console.WriteLine(s2.IndexOf(searchString, 2));
   }
}
// The example displays the following output:
//       4
//       3
Module Example
   Public Sub Main()
      Dim searchString As String = Chrw(&h00AD) + "m"
      Dim s1 As String = "ani" + ChrW(&h00AD) + "mal"
      Dim s2 As String = "animal"

      Console.WriteLine(s1.IndexOf(searchString, 2))
      Console.WriteLine(s2.IndexOf(searchString, 2))
   End Sub
End Module
' The example displays the following output:
'       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 substituent des valeurs par défaut et à la place appellent des méthodes qui requièrent des paramètres explicitement spécifiés.As explained in Best Practices for Using Strings, we recommend that you avoid calling string comparison methods that substitute default values and instead call methods that require parameters to be explicitly specified. Pour rechercher le premier index d’une sous-chaîne qui se produit après une position de caractère particulier en utilisant les règles de comparaison de la culture actuelle, appelez le IndexOf(String, Int32, StringComparison) surcharge de méthode avec une valeur de CurrentCulture pour son comparisonType paramètre.To find the first index of a substring that occurs after a particular character position by using the comparison rules of the current culture, call the IndexOf(String, Int32, StringComparison) method overload with a value of CurrentCulture for its comparisonType parameter.

Voir aussi

S’applique à