String.IndexOf Methode

Definitie

Rapporteert de op nul gebaseerde index van het eerste exemplaar van een opgegeven Unicode-teken of -tekenreeks in dit exemplaar. De methode retourneert -1 als het teken of de tekenreeks niet in dit exemplaar wordt gevonden.

Overloads

Name Description
IndexOf(Char, Int32, StringComparison)
IndexOf(Rune, Int32, Int32, StringComparison)
IndexOf(String, Int32, Int32, StringComparison)

Rapporteert de op nul gebaseerde index van het eerste exemplaar van de opgegeven tekenreeks in het huidige String object. Parameters geven de beginpositie op in de huidige tekenreeks, het aantal tekens in de huidige tekenreeks dat moet worden gezocht en het type zoekopdracht dat moet worden gebruikt voor de opgegeven tekenreeks.

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

Rapporteert de op nul gebaseerde index van het eerste exemplaar van de opgegeven tekenreeks in het huidige String object. Parameters geven de beginpositie op in de huidige tekenreeks en het type zoekopdracht dat moet worden gebruikt voor de opgegeven tekenreeks.

IndexOf(String, Int32, Int32)

Rapporteert de op nul gebaseerde index van het eerste exemplaar van de opgegeven tekenreeks in dit exemplaar. De zoekopdracht begint bij een opgegeven tekenpositie en onderzoekt een opgegeven aantal tekenposities.

IndexOf(Char, Int32, Int32)

Rapporteert de op nul gebaseerde index van het eerste exemplaar van het opgegeven teken in dit exemplaar. De zoekopdracht begint bij een opgegeven tekenpositie en onderzoekt een opgegeven aantal tekenposities.

IndexOf(Char)

Rapporteert de op nul gebaseerde index van het eerste exemplaar van het opgegeven Unicode-teken in deze tekenreeks.

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

Rapporteert de op nul gebaseerde index van het eerste exemplaar van de opgegeven tekenreeks in het huidige String object. Een parameter geeft het type zoekopdracht op dat moet worden gebruikt voor de opgegeven tekenreeks.

IndexOf(String, Int32)

Rapporteert de op nul gebaseerde index van het eerste exemplaar van de opgegeven tekenreeks in dit exemplaar. De zoekopdracht begint bij een opgegeven tekenpositie.

IndexOf(Char, StringComparison)

Rapporteert de op nul gebaseerde index van het eerste exemplaar van het opgegeven Unicode-teken in deze tekenreeks. Een parameter geeft het type zoekopdracht op dat moet worden gebruikt voor het opgegeven teken.

IndexOf(Char, Int32)

Rapporteert de op nul gebaseerde index van het eerste exemplaar van het opgegeven Unicode-teken in deze tekenreeks. De zoekopdracht begint bij een opgegeven tekenpositie.

IndexOf(Rune)
IndexOf(String)

Rapporteert de op nul gebaseerde index van het eerste exemplaar van de opgegeven tekenreeks in dit exemplaar.

IndexOf(Rune, StringComparison)

IndexOf(Char, Int32, StringComparison)

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

Parameters

value
Char
startIndex
Int32
comparisonType
StringComparison

Retouren

Van toepassing op

IndexOf(Rune, Int32, Int32, StringComparison)

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

Parameters

value
Rune
startIndex
Int32
count
Int32
comparisonType
StringComparison

Retouren

Van toepassing op

IndexOf(String, Int32, Int32, StringComparison)

Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs

Rapporteert de op nul gebaseerde index van het eerste exemplaar van de opgegeven tekenreeks in het huidige String object. Parameters geven de beginpositie op in de huidige tekenreeks, het aantal tekens in de huidige tekenreeks dat moet worden gezocht en het type zoekopdracht dat moet worden gebruikt voor de opgegeven tekenreeks.

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

Parameters

value
String

De tekenreeks die moet worden gezocht.

startIndex
Int32

De beginpositie van de zoekopdracht.

count
Int32

Het aantal tekenposities dat moet worden onderzocht.

comparisonType
StringComparison

Een van de opsommingswaarden waarmee de regels voor de zoekopdracht worden opgegeven.

Retouren

De op nul gebaseerde indexpositie van de value parameter vanaf het begin van het huidige exemplaar als deze tekenreeks wordt gevonden, of -1 als dat niet het geval is. Als value dat het is Empty, is startIndexde retourwaarde .

Uitzonderingen

value is null.

count of startIndex is negatief.

– of –

startIndex is groter dan de lengte van dit exemplaar.

– of –

count is groter dan de lengte van deze tekenreeks min startIndex.

comparisonType is geen geldige StringComparison waarde.

Voorbeelden

In het volgende voorbeeld ziet u drie overbelastingen van de IndexOf methode waarmee het eerste exemplaar van een tekenreeks in een andere tekenreeks wordt gevonden met behulp van verschillende waarden van de StringComparison opsomming.

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

open System
open System.Threading
open System.Globalization

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

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

// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"

let scValues = 
    [| StringComparison.CurrentCulture
       StringComparison.CurrentCultureIgnoreCase
       StringComparison.InvariantCulture
       StringComparison.InvariantCultureIgnoreCase
       StringComparison.Ordinal
       StringComparison.OrdinalIgnoreCase |]

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

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

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

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

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

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

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

// Search using different values of StringComparison.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.")
for sc in scValues do
    let loc = cat.IndexOf(CapitalAWithRing, sc)
    Console.WriteLine("Comparison: {0,-28} Location: {1,3}", 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.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
End Class

'
'Note: This code example was executed on a console whose user interface 
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the 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
'

Opmerkingen

Indexnummering begint vanaf 0 (nul). De startIndex parameter kan variëren van 0 tot de lengte van het tekenreeksexemplaren.

De zoekopdracht begint bij startIndex -1.startIndex + count Het teken op startIndex + count is niet opgenomen in de zoekopdracht.

De comparisonType parameter geeft aan om te zoeken naar de value parameter met behulp van de huidige of invariante cultuur, met behulp van een hoofdlettergevoelige of hoofdlettergevoelige zoekopdracht en het gebruik van woorden of rangtelwoordenvergelijkingsregels.

Notities voor bellers

Tekensets bevatten negeerbare tekens. Dit zijn tekens die niet worden overwogen bij het uitvoeren van een taalkundige of cultuurgevoelige vergelijking. In een cultuurgevoelige zoekopdracht (dat wil gezegd, indien comparisonType niet Ordinal of OrdinalIgnoreCase), als value het een onwetbaar teken bevat, is het resultaat gelijk aan het zoeken met dat teken dat is verwijderd. Als value de methode slechts uit een of meer negeerbare tekens bestaat, retourneert IndexOf(String, Int32, Int32, StringComparison)de startIndex methode altijd de positie van het teken waarop de zoekopdracht begint.

In het volgende voorbeeld wordt de IndexOf(String, Int32, Int32, StringComparison) methode gebruikt om de positie van een zacht afbreekstreepje (U+00AD) te vinden, gevolgd door een 'm' die begint in het derde tot en met zesde teken in twee tekenreeksen. Slechts één van de tekenreeksen bevat de vereiste subtekenreeks. Als het voorbeeld wordt uitgevoerd op het .NET Framework 4 of hoger, omdat het zachte afbreekstreepje een negeerbaar teken is, retourneert de methode de index van 'm' in de tekenreeks wanneer er een cultuurgevoelige vergelijking wordt uitgevoerd. Wanneer er echter een rangtelvergelijking wordt uitgevoerd, wordt de subtekenreeks alleen in de eerste tekenreeks gevonden. Houd er rekening mee dat in het geval van de eerste tekenreeks, die het zachte afbreekstreepje gevolgd door een 'm' bevat, de methode de index van het zachte afbreekstreepje niet retourneert, maar in plaats daarvan de index van de 'm' retourneert wanneer er een cultuurgevoelige vergelijking wordt uitgevoerd. De methode retourneert de index van het zachte afbreekstreepje in de eerste tekenreeks alleen wanneer er een rangtelvergelijking wordt uitgevoerd.

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, StringComparison.CurrentCulture));
        Console.WriteLine(s1.IndexOf(searchString, 2, 4, StringComparison.Ordinal));
        Console.WriteLine(s2.IndexOf(searchString, 2, 4, StringComparison.CurrentCulture));
        Console.WriteLine(s2.IndexOf(searchString, 2, 4, StringComparison.Ordinal));

        // The example displays the following output:
        //       4
        //       3
        //       3
        //       -1
    }
}
open System

let searchString = "\u00ADm"
let s1 = "ani\u00ADmal"
let s2 = "animal"

printfn $"{s1.IndexOf(searchString, 2, 4, StringComparison.CurrentCulture)}"
printfn $"{s1.IndexOf(searchString, 2, 4, StringComparison.Ordinal)}"
printfn $"{s2.IndexOf(searchString, 2, 4, StringComparison.CurrentCulture)}"
printfn $"{s2.IndexOf(searchString, 2, 4, StringComparison.Ordinal)}"

// The example displays the following output:
//       4
//       3
//       3
//       -1
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, StringComparison.CurrentCulture))
      Console.WriteLine(s1.IndexOf(searchString, 2, 4, StringComparison.Ordinal))
      Console.WriteLine(s2.IndexOf(searchString, 2, 4, StringComparison.CurrentCulture))
      Console.WriteLine(s2.IndexOf(searchString, 2, 4, StringComparison.Ordinal))
   End Sub
End Module
' The example displays the following output:
'       4
'       3
'       3
'       -1

Van toepassing op

IndexOf(Char, Int32, Int32, StringComparison)

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

Parameters

value
Char
startIndex
Int32
count
Int32
comparisonType
StringComparison

Retouren

Van toepassing op

IndexOf(Rune, Int32, StringComparison)

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

Parameters

value
Rune
startIndex
Int32
comparisonType
StringComparison

Retouren

Van toepassing op

IndexOf(Rune, Int32, Int32)

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

Parameters

value
Rune
startIndex
Int32
count
Int32

Retouren

Van toepassing op

IndexOf(String, Int32, StringComparison)

Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs

Rapporteert de op nul gebaseerde index van het eerste exemplaar van de opgegeven tekenreeks in het huidige String object. Parameters geven de beginpositie op in de huidige tekenreeks en het type zoekopdracht dat moet worden gebruikt voor de opgegeven tekenreeks.

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

Parameters

value
String

De tekenreeks die moet worden gezocht.

startIndex
Int32

De beginpositie van de zoekopdracht.

comparisonType
StringComparison

Een van de opsommingswaarden waarmee de regels voor de zoekopdracht worden opgegeven.

Retouren

De op nul gebaseerde indexpositie van de value parameter vanaf het begin van het huidige exemplaar als deze tekenreeks wordt gevonden, of -1 als dat niet het geval is. Als value dat het is Empty, is startIndexde retourwaarde .

Uitzonderingen

value is null.

startIndex is kleiner dan 0 (nul) of groter dan de lengte van deze tekenreeks.

comparisonType is geen geldige StringComparison waarde.

Voorbeelden

In het volgende voorbeeld ziet u drie overbelastingen van de IndexOf methode waarmee het eerste exemplaar van een tekenreeks in een andere tekenreeks wordt gevonden met behulp van verschillende waarden van de StringComparison opsomming.

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

open System
open System.Threading
open System.Globalization

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

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

// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"

let scValues = 
    [| StringComparison.CurrentCulture
       StringComparison.CurrentCultureIgnoreCase
       StringComparison.InvariantCulture
       StringComparison.InvariantCultureIgnoreCase
       StringComparison.Ordinal
       StringComparison.OrdinalIgnoreCase |]

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

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

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

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

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

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

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

// Search using different values of StringComparison.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.")
for sc in scValues do
    let loc = cat.IndexOf(CapitalAWithRing, sc)
    Console.WriteLine("Comparison: {0,-28} Location: {1,3}", 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.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
End Class

'
'Note: This code example was executed on a console whose user interface 
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the 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
'

Opmerkingen

Indexnummering begint vanaf 0. De startIndex parameter kan variëren van 0 tot de lengte van het tekenreeksexemplaren. Als startIndex deze gelijk is aan de lengte van het tekenreeksexemplaren, retourneert de methode -1.

De comparisonType parameter geeft aan om te zoeken naar de value parameter met behulp van de huidige of invariante cultuur, met behulp van een hoofdlettergevoelige of hoofdlettergevoelige zoekopdracht en het gebruik van woorden of rangtelwoordenvergelijkingsregels.

Notities voor bellers

Tekensets bevatten negeerbare tekens. Dit zijn tekens die niet worden overwogen bij het uitvoeren van een taalkundige of cultuurgevoelige vergelijking. In een cultuurgevoelige zoekopdracht (dat wil gezegd, indien comparisonType niet Ordinal of OrdinalIgnoreCase), als value het een onwetbaar teken bevat, is het resultaat gelijk aan het zoeken met dat teken dat is verwijderd. Als value de methode slechts uit een of meer negeerbare tekens bestaat, retourneert IndexOf(String, Int32, StringComparison)de startIndex methode altijd de positie van het teken waarop de zoekopdracht begint.

In het volgende voorbeeld wordt de IndexOf(String, Int32, StringComparison) methode gebruikt om de positie van een zacht afbreekstreepje (U+00AD) te vinden, gevolgd door een 'm' die begint met de derde tekenpositie in twee tekenreeksen. Slechts één van de tekenreeksen bevat de vereiste subtekenreeks. Als het voorbeeld wordt uitgevoerd op het .NET Framework 4 of hoger, omdat het zachte afbreekstreepje een negeerbaar teken is, retourneert de methode de index van 'm' in de tekenreeks wanneer er een cultuurgevoelige vergelijking wordt uitgevoerd. Houd er rekening mee dat in het geval van de eerste tekenreeks, die het zachte afbreekstreepje bevat, gevolgd door een 'm', de methode de index van het zachte afbreekstreepje niet retourneert, maar in plaats daarvan de index van de 'm' retourneert. De methode retourneert de index van het zachte afbreekstreepje in de eerste tekenreeks alleen wanneer er een rangtelvergelijking wordt uitgevoerd.

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, StringComparison.CurrentCulture));
        Console.WriteLine(s1.IndexOf(searchString, 2, StringComparison.Ordinal));
        Console.WriteLine(s2.IndexOf(searchString, 2, StringComparison.CurrentCulture));
        Console.WriteLine(s2.IndexOf(searchString, 2, StringComparison.Ordinal));

        // The example displays the following output:
        //       4
        //       3
        //       3
        //       -1
    }
}
open System

let searchString = "\u00ADm"
let s1 = "ani\u00ADmal"
let s2 = "animal"

printfn $"{s1.IndexOf(searchString, 2, StringComparison.CurrentCulture)}"
printfn $"{s1.IndexOf(searchString, 2, StringComparison.Ordinal)}"
printfn $"{s2.IndexOf(searchString, 2, StringComparison.CurrentCulture)}"
printfn $"{s2.IndexOf(searchString, 2, StringComparison.Ordinal)}"

// The example displays the following output:
//       4
//       3
//       3
//       -1
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, StringComparison.CurrentCulture))
      Console.WriteLine(s1.IndexOf(searchString, 2, StringComparison.Ordinal))
      Console.WriteLine(s2.IndexOf(searchString, 2, StringComparison.CurrentCulture))
      Console.WriteLine(s2.IndexOf(searchString, 2, StringComparison.Ordinal))
   End Sub
End Module
' The example displays the following output:
'       4
'       3
'       3
'       -1

Van toepassing op

IndexOf(String, Int32, Int32)

Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs

Rapporteert de op nul gebaseerde index van het eerste exemplaar van de opgegeven tekenreeks in dit exemplaar. De zoekopdracht begint bij een opgegeven tekenpositie en onderzoekt een opgegeven aantal tekenposities.

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

Parameters

value
String

De tekenreeks die moet worden gezocht.

startIndex
Int32

De beginpositie van de zoekopdracht.

count
Int32

Het aantal tekenposities dat moet worden onderzocht.

Retouren

De indexpositie op basis van nul vanaf value het begin van het huidige exemplaar als deze tekenreeks wordt gevonden, of -1 als dat niet het geval is. Als value dat het is Empty, is startIndexde retourwaarde .

Uitzonderingen

value is null.

count of startIndex is negatief.

– of –

startIndex is groter dan de lengte van deze tekenreeks.

– of –

count is groter dan de lengte van deze tekenreeks min startIndex.

Voorbeelden

In het volgende voorbeeld wordt de index gevonden van alle exemplaren van de tekenreeks 'he' binnen een subtekenreeks van een andere tekenreeks. Houd er rekening mee dat het aantal tekens dat moet worden doorzocht, opnieuw moet worden berekend voor elke zoekiteratie.

string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+---";
string br2 = "012345678901234567890123456789012345678901234567890123456789012345678";
string str = "Now is the time for all good men to come to the aid of their country.";
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 34 to 68.
0----+----1----+----2----+----3----+----4----+----5----+----6----+---
012345678901234567890123456789012345678901234567890123456789012345678
Now is the time for all good men to come to the aid of their country.

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

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

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

let mutable broken = false
let mutable at = 0
while (start <= last) && (at > -1) do
    // start+count must be a position within -str-.
    let count = last - start
    at <- str.IndexOf("he", start, count)
    if at = -1 then
        broken <- true
    else
        printf $"{at} "
        start <- at + 1
printfn ""

(*
This example produces the following results:

All occurrences of 'he' from position 34 to 68.
0----+----1----+----2----+----3----+----4----+----5----+----6----+---
012345678901234567890123456789012345678901234567890123456789012345678
Now is the time for all good men to come to the aid of their country.

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

*)
' Sample for String.IndexOf(String, Int32, Int32)
Class Sample
   
   Public Shared Sub Main()
      
      Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
      Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
      Dim str As String = "Now is the time for all good men to come to the aid of their party."
      Dim start As Integer
      Dim at As Integer
      Dim [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
End Class
'
'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
'
'

Opmerkingen

Indexnummering begint vanaf 0 (nul). De startIndex parameter kan variëren van 0 tot de lengte van het tekenreeksexemplaren.

Met deze methode wordt een woord (hoofdlettergevoelig en cultuurgevoelig) gezocht met behulp van de huidige cultuur. De zoekopdracht begint bij startIndex -1.startIndex + count Het teken op startIndex + count is niet opgenomen in de zoekopdracht.

Tekensets bevatten negeerbare tekens. Dit zijn tekens die niet worden overwogen bij het uitvoeren van een taalkundige of cultuurgevoelige vergelijking. In een cultuurgevoelige zoekopdracht, als value het een negeerbaar teken bevat, is het resultaat gelijk aan het zoeken met dat teken dat is verwijderd. Als value de methode slechts uit een of meer negeerbare tekens bestaat, retourneert IndexOf(String, Int32, Int32)de startIndex methode altijd de positie van het teken waarop de zoekopdracht begint. In het volgende voorbeeld wordt de IndexOf(String, Int32, Int32) methode gebruikt om de positie van een zacht afbreekstreepje (U+00AD) te vinden, gevolgd door een 'm' die begint in het derde tot en met zesde teken in twee tekenreeksen. Slechts één van de tekenreeksen bevat de vereiste subtekenreeks. Als het voorbeeld wordt uitgevoerd op het .NET Framework 4 of hoger, omdat het zachte afbreekstreepje een negeerbaar teken is, retourneert de methode de index van 'm' in de tekenreeks wanneer er een cultuurgevoelige vergelijking wordt uitgevoerd. Houd er rekening mee dat in het geval van de eerste tekenreeks, die het zachte afbreekstreepje bevat, gevolgd door een 'm', de methode de index van het zachte afbreekstreepje niet retourneert, maar in plaats daarvan de index van de 'm' retourneert.

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
    }
}
let searchString = "\u00ADm"
let s1 = "ani\u00ADmal"
let s2 = "animal"

printfn $"{s1.IndexOf(searchString, 2, 4)}"
printfn $"{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

Notities voor bellers

Zoals wordt uitgelegd in aanbevolen procedures voor het gebruik van tekenreeksen, raden we u aan om vergelijkingsmethoden voor tekenreeksen te vermijden die standaardwaarden vervangen en in plaats daarvan methoden aanroepen waarvoor parameters expliciet moeten worden opgegeven. Als u de vergelijkingsregels van de huidige cultuur wilt gebruiken om deze bewerking uit te voeren, moet u uw intentie expliciet aangeven door de methode overbelast te maken met een waarde voor IndexOf(String, Int32, Int32, StringComparison)CurrentCulture de comparisonType parameter. Als u geen taalbewuste vergelijking nodig hebt, kunt u overwegen .Ordinal

Zie ook

Van toepassing op

IndexOf(Char, Int32, Int32)

Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs

Rapporteert de op nul gebaseerde index van het eerste exemplaar van het opgegeven teken in dit exemplaar. De zoekopdracht begint bij een opgegeven tekenpositie en onderzoekt een opgegeven aantal tekenposities.

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

Parameters

value
Char

Een Unicode-teken om te zoeken.

startIndex
Int32

De beginpositie van de zoekopdracht.

count
Int32

Het aantal tekenposities dat moet worden onderzocht.

Retouren

De op nul gebaseerde indexpositie vanaf value het begin van de tekenreeks als dat teken wordt gevonden, of -1 als dat niet het is.

Uitzonderingen

count of startIndex is negatief.

– of –

startIndex is groter dan de lengte van deze tekenreeks.

– of –

count is groter dan de lengte van deze tekenreeks min startIndex.

Voorbeelden

In het volgende voorbeeld ziet u de IndexOf methode.

// 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, int, int ) method.
open System

let br1 =
    "0----+----1----+----2----+----3----+----" +
    "4----+----5----+----6----+----7"
let br2 =
    "0123456789012345678901234567890123456789" +
    "0123456789012345678901234567890"
let str =
    "ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi " +
    "ABCDEFGHI abcdefghi ABCDEFGHI"

printfn "This example of String.IndexOf( char, int, int )\ngenerates the following output."
printfn $"{Environment.NewLine}{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"

let findAllChar (target: char) (searched: string) =
    printf $"The character '{target}' occurs at position(s): "

    let mutable hitCount = 0
    let mutable startIndex = -1
    let mutable broken = false
    // Search for all occurrences of the target.
    while not broken do
        startIndex <- searched.IndexOf(target, startIndex + 1, searched.Length - startIndex - 1)

        // Exit the loop if the target is not found.
        if startIndex < 0 then
            broken <- true
        else

        printf $"{startIndex}, "
        hitCount <- hitCount + 1

    printfn $"occurrences: {hitCount}"

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, Integer, Integer ) method.
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
       
    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
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

Opmerkingen

De zoekopdracht begint bij startIndex -1.startIndex + count Het teken op startIndex + count is niet opgenomen in de zoekopdracht.

Indexnummering begint vanaf 0 (nul). De startIndex parameter kan variëren van 0 tot de lengte van het tekenreeksexemplaren.

Met deze methode wordt een ordinale (cultuurgevoelige) zoekopdracht uitgevoerd, waarbij een teken alleen wordt beschouwd als gelijkwaardig aan een ander teken als hun Unicode-scalaire waarden hetzelfde zijn. Als u een cultuurgevoelige zoekopdracht wilt uitvoeren, gebruikt u de CompareInfo.IndexOf methode, waarbij een Unicode-scalaire waarde die een vooraf samengesteld teken vertegenwoordigt, zoals de ligatuur 'Æ' (U+00C6), kan worden beschouwd als gelijkwaardig aan elk exemplaar van de onderdelen van het teken in de juiste volgorde, zoals 'AE' (U+0041, U+0045), afhankelijk van de cultuur.

Zie ook

Van toepassing op

IndexOf(Char)

Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs

Rapporteert de op nul gebaseerde index van het eerste exemplaar van het opgegeven Unicode-teken in deze tekenreeks.

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

Parameters

value
Char

Een Unicode-teken om te zoeken.

Retouren

De op nul gebaseerde indexpositie van value als dat teken wordt gevonden of -1 als dat niet het is.

Voorbeelden

In het volgende voorbeeld ziet u hoe u een String teken kunt zoeken met behulp van de IndexOf methode.

// 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: ΩΩΩΑΑΑΑΑΩΩΩ
//    First occurrence of the Greek letter Alpha: Index 3
//    First occurrence of the Greek letter Omega: Index 0
open System

// Create a Unicode string with 5 Greek Alpha characters.
let szGreekAlpha = String('\u0391',5)

// Create a Unicode string with 3 Greek Omega characters.
let szGreekOmega = "\u03A9\u03A9\u03A9"

let szGreekLetters = String.Concat(szGreekOmega, szGreekAlpha, szGreekOmega.Clone())

// Display the entire string.
printfn $"The string: {szGreekLetters}"

// The first index of Alpha.
let ialpha = szGreekLetters.IndexOf '\u0391'
// The first index of Omega.
let iomega = szGreekLetters.IndexOf '\u03A9'

printfn "First occurrence of the Greek letter Alpha: Index {ialpha}"
printfn "First occurrence of the Greek letter Omega: Index {iomega}"

// The example displays the following output:
//    The string: ΩΩΩΑΑΑΑΑΩΩΩ
//    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

Opmerkingen

Indexnummering begint vanaf nul.

Met deze methode wordt een ordinale (cultuurgevoelige) zoekopdracht uitgevoerd, waarbij een teken alleen wordt beschouwd als gelijkwaardig aan een ander teken als hun Unicode-scalaire waarden hetzelfde zijn. Als u een cultuurgevoelige zoekopdracht wilt uitvoeren, gebruikt u de CompareInfo.IndexOf methode, waarbij een Unicode-scalaire waarde die een vooraf samengesteld teken vertegenwoordigt, zoals de ligatuur 'Æ' (U+00C6), kan worden beschouwd als gelijkwaardig aan elk exemplaar van de onderdelen van het teken in de juiste volgorde, zoals 'AE' (U+0041, U+0045), afhankelijk van de cultuur.

Zie ook

Van toepassing op

IndexOf(Rune, Int32)

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

Parameters

value
Rune
startIndex
Int32

Retouren

Van toepassing op

IndexOf(String, StringComparison)

Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs

Rapporteert de op nul gebaseerde index van het eerste exemplaar van de opgegeven tekenreeks in het huidige String object. Een parameter geeft het type zoekopdracht op dat moet worden gebruikt voor de opgegeven tekenreeks.

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

Parameters

value
String

De tekenreeks die moet worden gezocht.

comparisonType
StringComparison

Een van de opsommingswaarden waarmee de regels voor de zoekopdracht worden opgegeven.

Retouren

De indexpositie van de value parameter als deze tekenreeks wordt gevonden of -1 als dat niet het is. Als value dat het is Empty, is de retourwaarde 0.

Uitzonderingen

value is null.

comparisonType is geen geldige StringComparison waarde.

Voorbeelden

In het volgende voorbeeld ziet u drie overbelastingen van de IndexOf methode waarmee het eerste exemplaar van een tekenreeks in een andere tekenreeks wordt gevonden met behulp van verschillende waarden van de StringComparison opsomming.

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

open System
open System.Threading
open System.Globalization

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

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

// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"

let scValues = 
    [| StringComparison.CurrentCulture
       StringComparison.CurrentCultureIgnoreCase
       StringComparison.InvariantCulture
       StringComparison.InvariantCultureIgnoreCase
       StringComparison.Ordinal
       StringComparison.OrdinalIgnoreCase |]

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

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

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

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

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

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

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

// Search using different values of StringComparison.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.")
for sc in scValues do
    let loc = cat.IndexOf(CapitalAWithRing, sc)
    Console.WriteLine("Comparison: {0,-28} Location: {1,3}", 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.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
End Class

'
'Note: This code example was executed on a console whose user interface 
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the 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
'

Opmerkingen

Indexnummering begint vanaf nul.

De comparisonType parameter geeft aan om te zoeken naar de value parameter met behulp van de huidige of invariante cultuur, met behulp van een hoofdlettergevoelige of hoofdlettergevoelige zoekopdracht en het gebruik van woorden of rangtelwoordenvergelijkingsregels.

Notities voor bellers

Tekensets bevatten negeerbare tekens. Dit zijn tekens die niet worden overwogen bij het uitvoeren van een taalkundige of cultuurgevoelige vergelijking. In een cultuurgevoelige zoekopdracht (dat wil gezegd, indien comparisonType niet Ordinal of OrdinalIgnoreCase), als value het een onwetbaar teken bevat, is het resultaat gelijk aan het zoeken met dat teken dat is verwijderd. Als value de methode slechts uit een of meer negeerbare tekens bestaat, retourneert de IndexOf(String, StringComparison) methode altijd 0 (nul) om aan te geven dat de overeenkomst aan het begin van het huidige exemplaar wordt gevonden.

In het volgende voorbeeld wordt de IndexOf(String, StringComparison) methode gebruikt om drie subtekenreeksen te vinden (een zacht afbreekstreepje (U+00AD), een zacht afbreekstreepje gevolgd door 'n' en een zacht afbreekstreepje gevolgd door 'm') in twee tekenreeksen. Slechts een van de tekenreeksen bevat een zacht afbreekstreepje. Als het voorbeeld wordt uitgevoerd op het .NET Framework 4 of hoger, omdat het zachte afbreekstreepje een negeerbaar teken is, retourneert een cultuurgevoelige zoekopdracht dezelfde waarde die wordt geretourneerd als het zachte afbreekstreepje niet is opgenomen in de zoekreeks. Een rangschikkingszoekopdracht vindt echter het zachte afbreekstreepje in één tekenreeks en rapporteert dat het niet aanwezig is in de tweede tekenreeks.

using System;

public class Example
{
    public static void Main()
    {
        string s1 = "ani\u00ADmal";
        string s2 = "animal";
      
        Console.WriteLine("Culture-sensitive comparison:");
        // Use culture-sensitive comparison to find the soft hyphen.
        Console.WriteLine(s1.IndexOf("\u00AD", StringComparison.CurrentCulture));
        Console.WriteLine(s2.IndexOf("\u00AD", StringComparison.CurrentCulture));
      
        // Use culture-sensitive comparison to find the soft hyphen followed by "n".
        Console.WriteLine(s1.IndexOf("\u00ADn", StringComparison.CurrentCulture));
        Console.WriteLine(s2.IndexOf("\u00ADn", StringComparison.CurrentCulture));
      
        // Use culture-sensitive comparison to find the soft hyphen followed by "m".
        Console.WriteLine(s1.IndexOf("\u00ADm", StringComparison.CurrentCulture));
        Console.WriteLine(s2.IndexOf("\u00ADm", StringComparison.CurrentCulture));
      
        Console.WriteLine("Ordinal comparison:");
        // Use ordinal comparison to find the soft hyphen.
        Console.WriteLine(s1.IndexOf("\u00AD", StringComparison.Ordinal));
        Console.WriteLine(s2.IndexOf("\u00AD", StringComparison.Ordinal));
      
        // Use ordinal comparison to find the soft hyphen followed by "n".
        Console.WriteLine(s1.IndexOf("\u00ADn", StringComparison.Ordinal));
        Console.WriteLine(s2.IndexOf("\u00ADn", StringComparison.Ordinal));
      
        // Use ordinal comparison to find the soft hyphen followed by "m".
        Console.WriteLine(s1.IndexOf("\u00ADm", StringComparison.Ordinal));
        Console.WriteLine(s2.IndexOf("\u00ADm", StringComparison.Ordinal));

        // The example displays the following output:
        //       Culture-sensitive comparison:
        //       0
        //       0
        //       1
        //       1
        //       4
        //       3
        //       Ordinal comparison:
        //       3
        //       -1
        //       -1
        //       -1
        //       3
        //       -1
    }
}
open System

let s1 = "ani\u00ADmal"
let s2 = "animal"

printfn "Culture-sensitive comparison:"
// Use culture-sensitive comparison to find the soft hyphen.
printfn $"""{s1.IndexOf("\u00AD", StringComparison.CurrentCulture)}"""
printfn $"""{s2.IndexOf("\u00AD", StringComparison.CurrentCulture)}"""

// Use culture-sensitive comparison to find the soft hyphen followed by "n".
printfn $"""{s1.IndexOf("\u00ADn", StringComparison.CurrentCulture)}"""
printfn $"""{s2.IndexOf("\u00ADn", StringComparison.CurrentCulture)}"""

// Use culture-sensitive comparison to find the soft hyphen followed by "m".
printfn $"""{s1.IndexOf("\u00ADm", StringComparison.CurrentCulture)}"""
printfn $"""{s2.IndexOf("\u00ADm", StringComparison.CurrentCulture)}"""

printfn "Ordinal comparison:"
// Use ordinal comparison to find the soft hyphen.
printfn $"""{s1.IndexOf("\u00AD", StringComparison.Ordinal)}"""
printfn $"""{s2.IndexOf("\u00AD", StringComparison.Ordinal)}"""

// Use ordinal comparison to find the soft hyphen followed by "n".
printfn $"""{s1.IndexOf("\u00ADn", StringComparison.Ordinal)}"""
printfn $"""{s2.IndexOf("\u00ADn", StringComparison.Ordinal)}"""

// Use ordinal comparison to find the soft hyphen followed by "m".
printfn $"""{s1.IndexOf("\u00ADm", StringComparison.Ordinal)}"""
printfn $"""{s2.IndexOf("\u00ADm", StringComparison.Ordinal)}"""

// The example displays the following output:
//       Culture-sensitive comparison:
//       0
//       0
//       1
//       1
//       4
//       3
//       Ordinal comparison:
//       3
//       -1
//       -1
//       -1
//       3
//       -1
Module Example
   Public Sub Main()
      Dim softHyphen As String = ChrW(&h00AD)
      Dim s1 As String = "ani" + softHyphen + "mal"
      Dim s2 As String = "animal"
      
      Console.WriteLine("Culture-sensitive comparison:")
      ' Use culture-sensitive comparison to find the soft hyphen.
      Console.WriteLine(s1.IndexOf(softHyphen, StringComparison.CurrentCulture))
      Console.WriteLine(s2.IndexOf(softHyphen, StringComparison.CurrentCulture))
      
      ' Use culture-sensitive comparison to find the soft hyphen followed by "n".
      Console.WriteLine(s1.IndexOf(softHyphen + "n", StringComparison.CurrentCulture))
      Console.WriteLine(s2.IndexOf(softHyphen + "n", StringComparison.CurrentCulture))
      
      ' Use culture-sensitive comparison to find the soft hyphen followed by "m".
      Console.WriteLine(s1.IndexOf(softHyphen + "m", StringComparison.CurrentCulture))
      Console.WriteLine(s2.IndexOf(softHyphen + "m", StringComparison.CurrentCulture))
      
      Console.WriteLine("Ordinal comparison:")
      ' Use ordinal comparison to find the soft hyphen.
      Console.WriteLine(s1.IndexOf(softHyphen, StringComparison.Ordinal))
      Console.WriteLine(s2.IndexOf(softHyphen, StringComparison.Ordinal))
      
      ' Use ordinal comparison to find the soft hyphen followed by "n".
      Console.WriteLine(s1.IndexOf(softHyphen + "n", StringComparison.Ordinal))
      Console.WriteLine(s2.IndexOf(softHyphen + "n", StringComparison.Ordinal))
      
      ' Use ordinal comparison to find the soft hyphen followed by "m".
      Console.WriteLine(s1.IndexOf(softHyphen + "m", StringComparison.Ordinal))
      Console.WriteLine(s2.IndexOf(softHyphen + "m", StringComparison.Ordinal))
   End Sub
End Module
' The example displays the following output:
'       Culture-sensitive comparison:
'       0
'       0
'       1
'       1
'       4
'       3
'       Ordinal comparison:
'       3
'       -1
'       -1
'       -1
'       3
'       -1

Van toepassing op

IndexOf(String, Int32)

Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs

Rapporteert de op nul gebaseerde index van het eerste exemplaar van de opgegeven tekenreeks in dit exemplaar. De zoekopdracht begint bij een opgegeven tekenpositie.

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

Parameters

value
String

De tekenreeks die moet worden gezocht.

startIndex
Int32

De beginpositie van de zoekopdracht.

Retouren

De indexpositie op basis van nul vanaf value het begin van het huidige exemplaar als deze tekenreeks wordt gevonden, of -1 als dat niet het geval is. Als value dat het is Empty, is startIndexde retourwaarde .

Uitzonderingen

value is null.

startIndex is kleiner dan 0 (nul) of groter dan de lengte van deze tekenreeks.

Voorbeelden

In het volgende voorbeeld wordt gezocht naar alle exemplaren van een opgegeven tekenreeks binnen een doeltekenreeks.

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 );
    }
}
open System

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

printfn $"The search string is:{Environment.NewLine}\"{strSource}\"{Environment.NewLine}"

let mutable broken = false
while not broken do
    let mutable totFinds = 0
    printf "Please enter a search value to look for in the above string (hit Enter to exit) => "

    let strTarget = stdin.ReadLine()

    if strTarget <> "" then
        let mutable i = 0
        let mutable broken = false
        while not broken && i <= strSource.Length - 1 do
            let found = strSource.IndexOf(strTarget, i)

            if found >= 0 then
                totFinds <- totFinds + 1
                i <- found
            else
                broken <- true
            i <- i + 1
    else
        broken <- true

    printfn $"{Environment.NewLine}The search parameter '{strTarget}' was found {totFinds} times.{Environment.NewLine}"
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
End Class

Opmerkingen

Indexnummering begint vanaf 0. De startIndex parameter kan variëren van 0 tot de lengte van het tekenreeksexemplaren. Als startIndex deze gelijk is aan de lengte van het tekenreeksexemplaren, retourneert de methode -1.

Met deze methode wordt een woord (hoofdlettergevoelig en cultuurgevoelig) gezocht met behulp van de huidige cultuur. De zoekopdracht begint op de startIndex tekenpositie van dit exemplaar en gaat door tot de laatste tekenpositie.

Tekensets bevatten negeerbare tekens. Dit zijn tekens die niet worden overwogen bij het uitvoeren van een taalkundige of cultuurgevoelige vergelijking. In een cultuurgevoelige zoekopdracht, als value het een negeerbaar teken bevat, is het resultaat gelijk aan het zoeken met dat teken dat is verwijderd. Als value de methode slechts uit een of meer negeerbare tekens bestaat, retourneert IndexOf(String, Int32)de startIndex methode altijd de positie van het teken waarop de zoekopdracht begint. In het volgende voorbeeld wordt de IndexOf(String, Int32) methode gebruikt om de positie van een zacht afbreekstreepje (U+00AD) te vinden, gevolgd door een 'm' in twee tekenreeksen. Slechts één van de tekenreeksen bevat de vereiste subtekenreeks. Als het voorbeeld wordt uitgevoerd op de .NET Framework 4 of hoger, in beide gevallen omdat het zachte afbreekstreepje een negeerbaar teken is, retourneert de methode de index van 'm' in de tekenreeks. Houd er rekening mee dat in het geval van de eerste tekenreeks, die het zachte afbreekstreepje bevat, gevolgd door een 'm', de methode de index van het zachte afbreekstreepje niet retourneert, maar in plaats daarvan de index van de 'm' retourneert.

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
    }
}
let searchString = "\u00ADm"
let s1 = "ani\u00ADmal"
let s2 = "animal"

printfn $"{s1.IndexOf(searchString, 2)}"
printfn $"{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

Notities voor bellers

Zoals wordt uitgelegd in aanbevolen procedures voor het gebruik van tekenreeksen, raden we u aan om vergelijkingsmethoden voor tekenreeksen te vermijden die standaardwaarden vervangen en in plaats daarvan methoden aanroepen waarvoor parameters expliciet moeten worden opgegeven. Als u de eerste index wilt vinden van een subtekenreeks die na een bepaalde tekenpositie plaatsvindt met behulp van de vergelijkingsregels van de huidige cultuur, moet u uw intentie expliciet aangeven door de IndexOf(String, Int32, StringComparison) methode overbelast te maken met een waarde voor CurrentCulture de comparisonType parameter. Als u geen taalbewuste vergelijking nodig hebt, kunt u overwegen .Ordinal

Zie ook

Van toepassing op

IndexOf(Char, StringComparison)

Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs

Rapporteert de op nul gebaseerde index van het eerste exemplaar van het opgegeven Unicode-teken in deze tekenreeks. Een parameter geeft het type zoekopdracht op dat moet worden gebruikt voor het opgegeven teken.

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

Parameters

value
Char

Het teken dat moet worden gezocht.

comparisonType
StringComparison

Een opsommingswaarde waarmee de regels voor de zoekopdracht worden opgegeven.

Retouren

De op nul gebaseerde index van value of dat teken wordt gevonden of -1 als dat niet het is.

Uitzonderingen

comparisonType is geen geldige StringComparison waarde.

Opmerkingen

Indexnummering begint vanaf nul.

De comparisonType parameter is een StringComparison opsommingslid dat aangeeft of de zoekopdracht naar het value argument gebruikmaakt van de huidige of invariante cultuur, hoofdlettergevoelig of niet hoofdlettergevoelig is, of woord- of rangtelwoordenvergelijkingsregels gebruikt.

Van toepassing op

IndexOf(Char, Int32)

Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs

Rapporteert de op nul gebaseerde index van het eerste exemplaar van het opgegeven Unicode-teken in deze tekenreeks. De zoekopdracht begint bij een opgegeven tekenpositie.

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

Parameters

value
Char

Een Unicode-teken om te zoeken.

startIndex
Int32

De beginpositie van de zoekopdracht.

Retouren

De op nul gebaseerde indexpositie vanaf value het begin van de tekenreeks als dat teken wordt gevonden, of -1 als dat niet het is.

Uitzonderingen

startIndex is kleiner dan 0 (nul) of groter dan de lengte van de tekenreeks.

Voorbeelden

In het volgende voorbeeld ziet u de IndexOf methode.

string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+---";
string br2 = "012345678901234567890123456789012345678901234567890123456789012345678";
string str = "Now is the time for all good men to come to the aid of their country.";
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 68.
0----+----1----+----2----+----3----+----4----+----5----+----6----+---
012345678901234567890123456789012345678901234567890123456789012345678
Now is the time for all good men to come to the aid of their country.

The letter 't' occurs at position(s): 7 11 33 41 44 55 65

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

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

let mutable at = 0
let mutable start = 0
let mutable broken = false
while not broken && (start < str.Length) && (at > -1) do
    at <- str.IndexOf('t', start)
    if at = -1 then broken <- true
    else
        printf $"{at} "
        start <- at + 1
    printfn ""

(*
This example produces the following results:

All occurrences of 't' from position 0 to 68.
0----+----1----+----2----+----3----+----4----+----5----+----6----+---
012345678901234567890123456789012345678901234567890123456789012345678
Now is the time for all good men to come to the aid of their country.

The letter 't' occurs at position(s): 7 11 33 41 44 55 65

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

Opmerkingen

Indexnummering begint vanaf 0. De startIndex parameter kan variëren van 0 tot de lengte van het tekenreeksexemplaren. Als startIndex deze gelijk is aan de lengte van het tekenreeksexemplaren, retourneert de methode -1.

De zoekbereiken van startIndex tot het einde van de tekenreeks.

Met deze methode wordt een ordinale (cultuurgevoelige) zoekopdracht uitgevoerd, waarbij een teken alleen wordt beschouwd als gelijkwaardig aan een ander teken als hun Unicode-scalaire waarden hetzelfde zijn. Als u een cultuurgevoelige zoekopdracht wilt uitvoeren, gebruikt u de CompareInfo.IndexOf methode, waarbij een Unicode-scalaire waarde die een vooraf samengesteld teken vertegenwoordigt, zoals de ligatuur 'Æ' (U+00C6), kan worden beschouwd als gelijkwaardig aan elk exemplaar van de onderdelen van het teken in de juiste volgorde, zoals 'AE' (U+0041, U+0045), afhankelijk van de cultuur.

Zie ook

Van toepassing op

IndexOf(Rune)

Bron:
String.Searching.cs
public:
 int IndexOf(System::Text::Rune value);
public int IndexOf(System.Text.Rune value);
member this.IndexOf : System.Text.Rune -> int
Public Function IndexOf (value As Rune) As Integer

Parameters

value
Rune

Retouren

Van toepassing op

IndexOf(String)

Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs
Bron:
String.Searching.cs

Rapporteert de op nul gebaseerde index van het eerste exemplaar van de opgegeven tekenreeks in dit exemplaar.

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

Parameters

value
String

De tekenreeks die moet worden gezocht.

Retouren

De op nul gebaseerde indexpositie van value als die tekenreeks wordt gevonden of -1 als deze niet is. Als value dat het is Empty, is de retourwaarde 0.

Uitzonderingen

value is null.

Voorbeelden

In het volgende voorbeeld wordt gezocht naar de 'n' in 'dier'. Omdat tekenreeksindexen beginnen bij nul in plaats van één, geeft de IndexOf(String) methode aan dat de 'n' zich op positie 1 bevindt.

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
open System

let str = "animal"
let toFind = "n"
let index = str.IndexOf "n"
printfn $"Found '{toFind}' in '{str}' at position {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

In het volgende voorbeeld wordt de IndexOf methode gebruikt om de beginpositie van een diernaam in een zin te bepalen. Vervolgens wordt deze positie gebruikt om een bijvoeglijk naamwoord in te voegen dat het dier in de zin beschrijft.

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.
open System

let animal1 = "fox"
let animal2 = "dog"

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

do
    printfn $"The original string is:{Environment.NewLine}{strTarget}{Environment.NewLine}"

    printf $"Enter an adjective (or group of adjectives) to describe the {animal1}: => "
    let adj1 = stdin.ReadLine()

    printf $"Enter an adjective (or group of adjectives) to describe the {animal2}: => "
    let adj2 = stdin.ReadLine()

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

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

    printfn $"{Environment.NewLine}The final string is:{strTarget}{Environment.NewLine}"
// 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.

Opmerkingen

Indexnummering begint vanaf nul.

Met deze methode wordt een woord (hoofdlettergevoelig en cultuurgevoelig) gezocht met behulp van de huidige cultuur. De zoekopdracht begint op de eerste tekenpositie van dit exemplaar en gaat door tot de laatste tekenpositie.

Tekensets bevatten negeerbare tekens. Dit zijn tekens die niet worden overwogen bij het uitvoeren van een taalkundige of cultuurgevoelige vergelijking. In een cultuurgevoelige zoekopdracht, als value het een negeerbaar teken bevat, is het resultaat gelijk aan het zoeken met dat teken dat is verwijderd. Als value de methode slechts uit een of meer negeerbare tekens bestaat, retourneert de IndexOf(String) methode altijd 0 (nul) om aan te geven dat de overeenkomst aan het begin van het huidige exemplaar wordt gevonden. In het volgende voorbeeld wordt de IndexOf(String) methode gebruikt om drie subtekenreeksen te vinden (een zacht afbreekstreepje (U+00AD), een zacht afbreekstreepje gevolgd door 'n' en een zacht afbreekstreepje gevolgd door 'm') in twee tekenreeksen. Slechts een van de tekenreeksen bevat een zacht afbreekstreepje. Als het voorbeeld wordt uitgevoerd op de .NET Framework 4 of hoger, in elk geval omdat het zachte afbreekstreepje een negeerbaar teken is, is het resultaat hetzelfde als als als het zachte afbreekstreepje niet is opgenomen in value. Wanneer u alleen zoekt naar een zacht afbreekstreepje, retourneert de methode 0 (nul) om aan te geven dat er een overeenkomst is gevonden aan het begin van de tekenreeks.

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
    }
}
let s1 = "ani\u00ADmal"
let s2 = "animal"

// Find the index of the soft hyphen.
printfn $"""{s1.IndexOf "\u00AD"}"""
printfn $"""{s2.IndexOf "\u00AD"}"""

// Find the index of the soft hyphen followed by "n".
printfn $"""{s1.IndexOf "\u00ADn"}"""
printfn $"""{s2.IndexOf "\u00ADn"}"""

// Find the index of the soft hyphen followed by "m".
printfn $"""{s1.IndexOf "\u00ADm"}"""
printfn $"""{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

Notities voor bellers

Zoals wordt uitgelegd in aanbevolen procedures voor het gebruik van tekenreeksen, raden we u aan om vergelijkingsmethoden voor tekenreeksen te vermijden die standaardwaarden vervangen en in plaats daarvan methoden aanroepen waarvoor parameters expliciet moeten worden opgegeven. Als u de eerste index van een subtekenreeks binnen een tekenreeksexemplaren wilt vinden met behulp van de vergelijkingsregels van de huidige cultuur, signaleert u uw intentie expliciet door de overbelasting van de IndexOf(String, StringComparison) methode aan te roepen met een waarde voor CurrentCulture de comparisonType parameter. Als u geen taalbewuste vergelijking nodig hebt, kunt u overwegen .Ordinal

Zie ook

Van toepassing op

IndexOf(Rune, StringComparison)

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

Parameters

value
Rune
comparisonType
StringComparison

Retouren

Van toepassing op