String.IndexOf Metoda
Definicja
Ważne
Niektóre informacje odnoszą się do produktu w wersji wstępnej, który może zostać znacząco zmodyfikowany przed wydaniem. Firma Microsoft nie udziela żadnych gwarancji, jawnych lub domniemanych, w odniesieniu do informacji podanych w tym miejscu.
Raportuje indeks od zera pierwszego wystąpienia określonego znaku Unicode lub ciągu w tym wystąpieniu. Metoda zwraca wartość -1, jeśli znak lub ciąg nie zostaną znalezione w tym wystąpieniu.
Przeciążenia
IndexOf(String, Int32, Int32, StringComparison) |
Raporty indeksu od zera pierwszego wystąpienia określonego ciągu w bieżącym String obiekcie. Parametry określają początkową pozycję wyszukiwania w bieżącym ciągu, liczbę znaków w bieżącym ciągu do wyszukania oraz typ wyszukiwania do użycia dla określonego ciągu. |
IndexOf(String, Int32, StringComparison) |
Raporty indeksu od zera pierwszego wystąpienia określonego ciągu w bieżącym String obiekcie. Parametry określają początkową pozycję wyszukiwania w bieżącym ciągu i typ wyszukiwania do użycia dla określonego ciągu. |
IndexOf(Char, Int32, Int32) |
Raportuje indeks od zera pierwszego wystąpienia określonego znaku w tym wystąpieniu. Wyszukiwanie rozpoczyna się od określonej pozycji znaku i sprawdza określoną liczbę pozycji znaków. |
IndexOf(String, StringComparison) |
Raporty indeksu od zera pierwszego wystąpienia określonego ciągu w bieżącym String obiekcie. Parametr określa typ wyszukiwania do użycia dla określonego ciągu. |
IndexOf(String, Int32, Int32) |
Raportuje indeks od zera pierwszego wystąpienia określonego ciągu w tym wystąpieniu. Wyszukiwanie rozpoczyna się od określonej pozycji znaku i sprawdza określoną liczbę pozycji znaków. |
IndexOf(Char, StringComparison) |
Raportuje indeks od zera pierwszego wystąpienia określonego znaku Unicode w tym ciągu. Parametr określa typ wyszukiwania dla określonego znaku. |
IndexOf(Char, Int32) |
Raportuje indeks od zera pierwszego wystąpienia określonego znaku Unicode w tym ciągu. Wyszukiwanie rozpoczyna się od określonej pozycji znaku. |
IndexOf(String) |
Raportuje indeks od zera pierwszego wystąpienia określonego ciągu w tym wystąpieniu. |
IndexOf(Char) |
Raportuje indeks od zera pierwszego wystąpienia określonego znaku Unicode w tym ciągu. |
IndexOf(String, Int32) |
Raportuje indeks od zera pierwszego wystąpienia określonego ciągu w tym wystąpieniu. Wyszukiwanie rozpoczyna się od określonej pozycji znaku. |
IndexOf(String, Int32, Int32, StringComparison)
Raporty indeksu od zera pierwszego wystąpienia określonego ciągu w bieżącym String obiekcie. Parametry określają początkową pozycję wyszukiwania w bieżącym ciągu, liczbę znaków w bieżącym ciągu do wyszukania oraz typ wyszukiwania do użycia dla określonego ciągu.
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
Parametry
- value
- String
Ciąg do wyszukania.
- startIndex
- Int32
Pozycja rozpoczęcia wyszukiwania.
- count
- Int32
Liczba pozycji znaku do zbadania.
- comparisonType
- StringComparison
Jedną z wartości wyliczenia, które określa reguły dotyczące wyszukiwania.
Zwraca
Pozycja indeksu od zera parametru od początku bieżącego wystąpienia, jeśli ten ciąg zostanie znaleziony, lub value
-1, jeśli nie jest. Jeśli value
wartość to , Empty zwracana wartość to startIndex
.
Wyjątki
value
to null
.
count
wartość lub startIndex
jest ujemna.
-lub-
startIndex
wartość jest większa niż długość tego wystąpienia.
-lub-
count
wartość jest większa niż długość tego ciągu minus startIndex
.
comparisonType
nie jest prawidłową StringComparison wartością.
Przykłady
W poniższym przykładzie pokazano trzy przeciążenia metody, które znajdują pierwsze wystąpienie ciągu w innym ciągu przy użyciu różnych IndexOf wartości StringComparison wyliczenia.
// This code example demonstrates the
// System.String.IndexOf(String, ..., StringComparison) methods.
using System;
using System.Threading;
using System.Globalization;
class Sample
{
public static void Main()
{
string intro = "Find the first occurrence of a character using different " +
"values of StringComparison.";
string resultFmt = "Comparison: {0,-28} Location: {1,3}";
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
string CapitalAWithRing = "\u00c5";
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
string cat = "A Cheshire c" + "\u0061\u030a" + "t";
int loc = 0;
StringComparison[] scValues = {
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
StringComparison.OrdinalIgnoreCase };
// Clear the screen and display an introduction.
Console.Clear();
Console.WriteLine(intro);
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("The current culture is \"{0}\" - {1}.",
Thread.CurrentThread.CurrentCulture.Name,
Thread.CurrentThread.CurrentCulture.DisplayName);
// Display the string to search for and the string to search.
Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"",
CapitalAWithRing, cat);
Console.WriteLine();
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparison. Specify the start
// index and count.
Console.WriteLine("Part 1: Start index and count are specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.IndexOf(CapitalAWithRing, 0, cat.Length, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparison. Specify the
// start index.
Console.WriteLine("\nPart 2: Start index is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.IndexOf(CapitalAWithRing, 0, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparison.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.IndexOf(CapitalAWithRing, sc);
Console.WriteLine(resultFmt, sc, loc);
}
}
}
/*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the first occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*/
' This code example demonstrates the
' System.String.IndexOf(String, ..., StringComparison) methods.
Imports System.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
'
Uwagi
Numerowanie indeksu zaczyna się od 0 (zero). Parametr startIndex
może mieć wartość od 0 do długości wystąpienia ciągu.
Wyszukiwanie rozpoczyna się od startIndex
i kontynuuje do startIndex
+ count
-1. Znak w startIndex
+ count
poleceniu nie jest uwzględniany w wyszukiwaniu.
Parametr określa wyszukiwanie parametru przy użyciu bieżącej lub niezmiennej kultury, przy użyciu wyszukiwania z rozróżnianą wielkością liter lub bez uwzględniania wielkości liter oraz przy użyciu reguł porównywania wyrazów lub comparisonType
value
porządkowych.
Uwagi dotyczące wywoływania
Zestawy znaków zawierają znaki do pominięcia. Są to znaki nieuwzględniane podczas porównywania pod względem językowym lub z uwzględnieniem ustawień kulturowych. W wyszukiwaniu z rozróżnianą kulturą (czyli jeśli element nie ma znaku lub ), jeśli zawiera znak do zignorowania, wynik jest odpowiednikiem wyszukiwania za pomocą comparisonType
Ordinal OrdinalIgnoreCase value
usuniętego znaku. Jeśli składa się tylko z jednego lub większej liczby znaków do zignorowania, metoda zawsze zwraca wartość , czyli pozycję value
IndexOf(String, Int32, Int32, StringComparison) startIndex
znaku, od której rozpoczyna się wyszukiwanie.
W poniższym przykładzie metoda jest używana do znalezienia pozycji łącznika programowego IndexOf(String, Int32, Int32, StringComparison) (U+00AD), po którym następuje znak "m", zaczynając od trzeciej do szóstej pozycji znaku w dwóch ciągach. Tylko jeden z ciągów zawiera wymagany podciąg. Jeśli przykład jest uruchamiany na platformie .NET Framework 4 lub nowszej, w obu przypadkach, ponieważ łącznik nieciągły jest znakiem do zignorowania, metoda zwraca indeks "m" w ciągu podczas wykonywania porównania z rozróżnianą kulturą. Jednak podczas wykonywania porównania porządkowego znajduje podciąg tylko w pierwszym ciągu. Należy pamiętać, że w przypadku pierwszego ciągu, który zawiera łącznik nieciągły, po którym następuje "m", metoda nie zwraca indeksu łącznika nie programowego, ale zamiast tego zwraca indeks "m" podczas porównywania z uwzględnianą kulturą. Metoda ta zwraca indeks łącznika nietrwałego w pierwszym ciągu tylko wtedy, gdy wykonuje porównanie porządkowe.
Dotyczy
IndexOf(String, Int32, StringComparison)
Raporty indeksu od zera pierwszego wystąpienia określonego ciągu w bieżącym String obiekcie. Parametry określają początkową pozycję wyszukiwania w bieżącym ciągu i typ wyszukiwania do użycia dla określonego ciągu.
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
Parametry
- value
- String
Ciąg do wyszukania.
- startIndex
- Int32
Pozycja rozpoczęcia wyszukiwania.
- comparisonType
- StringComparison
Jedną z wartości wyliczenia, które określa reguły dotyczące wyszukiwania.
Zwraca
Pozycja indeksu od zera parametru od początku bieżącego wystąpienia, jeśli ten ciąg zostanie znaleziony, lub value
-1, jeśli nie jest. Jeśli value
wartość to , Empty zwracana wartość to startIndex
.
Wyjątki
value
to null
.
startIndex
jest mniejsza niż 0 (zero) lub większa niż długość tego ciągu.
comparisonType
nie jest prawidłową StringComparison wartością.
Przykłady
W poniższym przykładzie pokazano trzy przeciążenia metody, które znajdują pierwsze wystąpienie ciągu w innym ciągu przy użyciu różnych IndexOf wartości StringComparison wyliczenia.
// This code example demonstrates the
// System.String.IndexOf(String, ..., StringComparison) methods.
using System;
using System.Threading;
using System.Globalization;
class Sample
{
public static void Main()
{
string intro = "Find the first occurrence of a character using different " +
"values of StringComparison.";
string resultFmt = "Comparison: {0,-28} Location: {1,3}";
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
string CapitalAWithRing = "\u00c5";
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
string cat = "A Cheshire c" + "\u0061\u030a" + "t";
int loc = 0;
StringComparison[] scValues = {
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
StringComparison.OrdinalIgnoreCase };
// Clear the screen and display an introduction.
Console.Clear();
Console.WriteLine(intro);
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("The current culture is \"{0}\" - {1}.",
Thread.CurrentThread.CurrentCulture.Name,
Thread.CurrentThread.CurrentCulture.DisplayName);
// Display the string to search for and the string to search.
Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"",
CapitalAWithRing, cat);
Console.WriteLine();
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparison. Specify the start
// index and count.
Console.WriteLine("Part 1: Start index and count are specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.IndexOf(CapitalAWithRing, 0, cat.Length, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparison. Specify the
// start index.
Console.WriteLine("\nPart 2: Start index is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.IndexOf(CapitalAWithRing, 0, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparison.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.IndexOf(CapitalAWithRing, sc);
Console.WriteLine(resultFmt, sc, loc);
}
}
}
/*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the first occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*/
' This code example demonstrates the
' System.String.IndexOf(String, ..., StringComparison) methods.
Imports System.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
'
Uwagi
Numerowanie indeksu zaczyna się od 0. Parametr startIndex
może mieć wartość od 0 do długości wystąpienia ciągu. Jeśli startIndex
jest równa długości wystąpienia ciągu, metoda zwraca wartość -1.
Parametr określa wyszukiwanie parametru przy użyciu bieżącej lub niezmiennej kultury, przy użyciu wyszukiwania z rozróżnianą wielkością liter lub bez uwzględniania wielkości liter oraz przy użyciu reguł porównywania wyrazów lub comparisonType
value
porządkowych.
Uwagi dotyczące wywoływania
Zestawy znaków zawierają znaki do pominięcia. Są to znaki nieuwzględniane podczas porównywania pod względem językowym lub z uwzględnieniem ustawień kulturowych. W wyszukiwaniu z rozróżnianą kulturą (czyli jeśli element nie ma znaku lub ), jeśli zawiera znak do zignorowania, wynik jest odpowiednikiem wyszukiwania za pomocą comparisonType
Ordinal OrdinalIgnoreCase value
usuniętego znaku. Jeśli składa się tylko z jednego lub większej liczby znaków do zignorowania, metoda zawsze zwraca wartość , czyli pozycję value
IndexOf(String, Int32, StringComparison) startIndex
znaku, od której rozpoczyna się wyszukiwanie.
W poniższym przykładzie metoda jest używana do znalezienia pozycji łącznika programowego IndexOf(String, Int32, StringComparison) (U+00AD), po którym następuje znak "m", zaczynając od trzeciej pozycji znaku w dwóch ciągach. Tylko jeden z ciągów zawiera wymagany podciąg. Jeśli przykład jest uruchamiany na platformie .NET Framework 4 lub nowszej, w obu przypadkach, ponieważ łącznik nieciągły jest znakiem do zignorowania, metoda zwraca indeks "m" w ciągu podczas wykonywania porównania z rozróżnianą kulturą. Należy pamiętać, że w przypadku pierwszego ciągu, który zawiera łącznik nietrwały, a po nim „m”, metoda nie zwraca indeksu łącznika nietrwałego, ale zamiast tego zwraca indeks „m”. Metoda ta zwraca indeks łącznika nietrwałego w pierwszym ciągu tylko wtedy, gdy wykonuje porównanie porządkowe.
Dotyczy
IndexOf(Char, Int32, Int32)
Raportuje indeks od zera pierwszego wystąpienia określonego znaku w tym wystąpieniu. Wyszukiwanie rozpoczyna się od określonej pozycji znaku i sprawdza określoną liczbę pozycji znaków.
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
Parametry
- value
- Char
Znak Unicode do szukania.
- startIndex
- Int32
Pozycja rozpoczęcia wyszukiwania.
- count
- Int32
Liczba pozycji znaku do zbadania.
Zwraca
Pozycja indeksu od zera od początku ciągu, jeśli ten znak zostanie znaleziony, lub value
-1, jeśli nie jest.
Wyjątki
count
wartość lub startIndex
jest ujemna.
-lub-
startIndex
wartość jest większa niż długość tego ciągu.
-lub-
count
wartość jest większa niż długość tego ciągu minus startIndex
.
Przykłady
W poniższym przykładzie pokazano IndexOf metodę .
// Example for the String::IndexOf( Char, int, int ) method.
using namespace System;
void FindAllChar( Char target, String^ searched )
{
Console::Write( "The character '{0}' occurs at position(s): ", target );
int startIndex = -1;
int hitCount = 0;
// Search for all occurrences of the target.
while ( true )
{
startIndex = searched->IndexOf( target, startIndex + 1, searched->Length - startIndex - 1 );
// Exit the loop if the target is not found.
if ( startIndex < 0 )
break;
Console::Write( "{0}, ", startIndex );
hitCount++;
}
Console::WriteLine( "occurrences: {0}", hitCount );
}
int main()
{
String^ br1 = "0----+----1----+----2----+----3----+----"
"4----+----5----+----6----+----7";
String^ br2 = "0123456789012345678901234567890123456789"
"0123456789012345678901234567890";
String^ str = "ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi "
"ABCDEFGHI abcdefghi ABCDEFGHI";
Console::WriteLine( "This example of String::IndexOf( Char, int, int )\n"
"generates the following output." );
Console::WriteLine( "{0}{1}{0}{2}{0}{3}{0}", Environment::NewLine, br1, br2, str );
FindAllChar( 'A', str );
FindAllChar( 'a', str );
FindAllChar( 'I', str );
FindAllChar( 'i', str );
FindAllChar( '@', str );
FindAllChar( ' ', str );
}
/*
This example of String::IndexOf( Char, int, int )
generates the following output.
0----+----1----+----2----+----3----+----4----+----5----+----6----+----7
01234567890123456789012345678901234567890123456789012345678901234567890
ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI
The character 'A' occurs at position(s): 0, 20, 40, 60, occurrences: 4
The character 'a' occurs at position(s): 10, 30, 50, occurrences: 3
The character 'I' occurs at position(s): 8, 28, 48, 68, occurrences: 4
The character 'i' occurs at position(s): 18, 38, 58, occurrences: 3
The character '@' occurs at position(s): occurrences: 0
The character ' ' occurs at position(s): 9, 19, 29, 39, 49, 59, occurrences: 6
*/
// Example for the String.IndexOf( char, int, int ) method.
using System;
class IndexOfCII
{
public static void Main()
{
string br1 =
"0----+----1----+----2----+----3----+----" +
"4----+----5----+----6----+----7";
string br2 =
"0123456789012345678901234567890123456789" +
"0123456789012345678901234567890";
string str =
"ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi " +
"ABCDEFGHI abcdefghi ABCDEFGHI";
Console.WriteLine(
"This example of String.IndexOf( char, int, int )\n" +
"generates the following output." );
Console.WriteLine(
"{0}{1}{0}{2}{0}{3}{0}",
Environment.NewLine, br1, br2, str );
FindAllChar( 'A', str );
FindAllChar( 'a', str );
FindAllChar( 'I', str );
FindAllChar( 'i', str );
FindAllChar( '@', str );
FindAllChar( ' ', str );
}
static void FindAllChar( Char target, String searched )
{
Console.Write(
"The character '{0}' occurs at position(s): ",
target );
int startIndex = -1;
int hitCount = 0;
// Search for all occurrences of the target.
while( true )
{
startIndex = searched.IndexOf(
target, startIndex + 1,
searched.Length - startIndex - 1 );
// Exit the loop if the target is not found.
if( startIndex < 0 )
break;
Console.Write( "{0}, ", startIndex );
hitCount++;
}
Console.WriteLine( "occurrences: {0}", hitCount );
}
}
/*
This example of String.IndexOf( char, int, int )
generates the following output.
0----+----1----+----2----+----3----+----4----+----5----+----6----+----7
01234567890123456789012345678901234567890123456789012345678901234567890
ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi ABCDEFGHI
The character 'A' occurs at position(s): 0, 20, 40, 60, occurrences: 4
The character 'a' occurs at position(s): 10, 30, 50, occurrences: 3
The character 'I' occurs at position(s): 8, 28, 48, 68, occurrences: 4
The character 'i' occurs at position(s): 18, 38, 58, occurrences: 3
The character '@' occurs at position(s): occurrences: 0
The character ' ' occurs at position(s): 9, 19, 29, 39, 49, 59, occurrences: 6
*/
' Example for the String.IndexOf( Char, Integer, Integer ) method.
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
Uwagi
Wyszukiwanie rozpoczyna się od startIndex
i kontynuuje do startIndex
+ count
-1. Znak w startIndex
+ count
at nie jest uwzględniony w wyszukiwaniu.
Numerowanie indeksu zaczyna się od 0 (zero). Parametr startIndex
może mieć wartość od 0 do długości wystąpienia ciągu.
Ta metoda przeprowadza wyszukiwanie porządkowe (niewrażliwość na ustawienia kulturowe), gdzie znak jest uważany za równoważny innemu znakowi tylko wtedy, gdy ich wartości skalarne Unicode są takie same. Aby przeprowadzić wyszukiwanie zależne od kultury, użyj metody , w której wartość skalarna Unicode reprezentująca wstępnie skompilowany znak, taką jak "AE" (U+00C6), może być uważana za równoważną dowolnemu wystąpieniu składników znaku w prawidłowej sekwencji, takim jak CompareInfo.IndexOf "AE" (U+0041, U+0045), w zależności od kultury.
Zobacz też
Dotyczy
IndexOf(String, StringComparison)
Raporty indeksu od zera pierwszego wystąpienia określonego ciągu w bieżącym String obiekcie. Parametr określa typ wyszukiwania do użycia dla określonego ciągu.
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
Parametry
- value
- String
Ciąg do wyszukania.
- comparisonType
- StringComparison
Jedną z wartości wyliczenia, które określa reguły dotyczące wyszukiwania.
Zwraca
Pozycja indeksu value
parametru, jeśli ten ciąg zostanie znaleziony, lub -1, jeśli nie jest. Jeśli value
wartość to , Empty zwracana wartość to 0.
Wyjątki
value
to null
.
comparisonType
nie jest prawidłową StringComparison wartością.
Przykłady
W poniższym przykładzie przedstawiono trzy przeciążenia metody, które znajdują pierwsze wystąpienie ciągu w innym ciągu przy użyciu IndexOf różnych wartości StringComparison wyliczenia.
// This code example demonstrates the
// System.String.IndexOf(String, ..., StringComparison) methods.
using System;
using System.Threading;
using System.Globalization;
class Sample
{
public static void Main()
{
string intro = "Find the first occurrence of a character using different " +
"values of StringComparison.";
string resultFmt = "Comparison: {0,-28} Location: {1,3}";
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
string CapitalAWithRing = "\u00c5";
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
string cat = "A Cheshire c" + "\u0061\u030a" + "t";
int loc = 0;
StringComparison[] scValues = {
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
StringComparison.OrdinalIgnoreCase };
// Clear the screen and display an introduction.
Console.Clear();
Console.WriteLine(intro);
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("The current culture is \"{0}\" - {1}.",
Thread.CurrentThread.CurrentCulture.Name,
Thread.CurrentThread.CurrentCulture.DisplayName);
// Display the string to search for and the string to search.
Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"",
CapitalAWithRing, cat);
Console.WriteLine();
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparison. Specify the start
// index and count.
Console.WriteLine("Part 1: Start index and count are specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.IndexOf(CapitalAWithRing, 0, cat.Length, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparison. Specify the
// start index.
Console.WriteLine("\nPart 2: Start index is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.IndexOf(CapitalAWithRing, 0, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparison.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.IndexOf(CapitalAWithRing, sc);
Console.WriteLine(resultFmt, sc, loc);
}
}
}
/*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the first occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*/
' This code example demonstrates the
' System.String.IndexOf(String, ..., StringComparison) methods.
Imports System.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
'
Uwagi
Indeks numerowania rozpoczyna się od zera.
Parametr określa wyszukiwanie parametru przy użyciu bieżącej lub niezmiennej kultury, przy użyciu wyszukiwania z rozróżnianą wielkością liter lub bez uwzględniania wielkości liter oraz przy użyciu reguł porównywania wyrazów lub comparisonType
value
porządkowych.
Uwagi dotyczące wywoływania
Zestawy znaków zawierają znaki do pominięcia. Są to znaki nieuwzględniane podczas porównywania pod względem językowym lub z uwzględnieniem ustawień kulturowych. W wyszukiwaniu z rozróżnianą kulturą (to oznacza, że jeśli nie jest znakiem lub ), jeśli zawiera znak do zignorowania, wynik jest odpowiednikiem wyszukiwania za pomocą comparisonType
Ordinal tego znaku OrdinalIgnoreCase value
usuniętego. Jeśli składa się tylko z jednego lub większej liczby ignorowanych znaków, metoda zawsze zwraca value
wartość 0 (zero), aby wskazać, że dopasowanie znajduje się na IndexOf(String, StringComparison) początku bieżącego wystąpienia.
W poniższym przykładzie metoda jest używana do znalezienia trzech podciągów (łącznika programowego (U+00AD), łącznika programowego, po którym następuje "n" i łącznika programowego, po którym następuje "m") w dwóch IndexOf(String, StringComparison) ciągach. Tylko jeden z ciągów zawiera łącznik nietrwały. Jeśli przykład jest uruchamiany na platformie .NET Framework 4 lub nowszej, ponieważ łącznik nieciągły jest znakiem do zignorowania, wyszukiwanie z uwzględnianą kulturą zwraca tę samą wartość, która zostanie zwrócona, jeśli łącznik nieciągły nie został uwzględniony w ciągu wyszukiwania. Jednak wyszukiwanie porządkowe pomyślnie znajduje łącznik nieciągły w jednym ciągu i zgłasza, że jest on nieobecny w drugim ciągu.
Dotyczy
IndexOf(String, Int32, Int32)
Raportuje indeks od zera pierwszego wystąpienia określonego ciągu w tym wystąpieniu. Wyszukiwanie rozpoczyna się od określonej pozycji znaku i sprawdza określoną liczbę pozycji znaków.
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
Parametry
- value
- String
Ciąg do wyszukania.
- startIndex
- Int32
Pozycja rozpoczęcia wyszukiwania.
- count
- Int32
Liczba pozycji znaku do zbadania.
Zwraca
Pozycja indeksu od zera od początku bieżącego wystąpienia, jeśli ten ciąg zostanie znaleziony, lub value
-1, jeśli nie jest. Jeśli value
wartość to , Empty zwracana wartość to startIndex
.
Wyjątki
value
to null
.
count
wartość lub startIndex
jest ujemna.
-lub-
startIndex
wartość jest większa niż długość tego ciągu.
-lub-
count
wartość jest większa niż długość tego ciągu minus startIndex
.
Przykłady
Poniższy przykład znajduje indeks wszystkich wystąpień ciągu "he" w podciągu innego ciągu. Należy pamiętać, że dla każdej iteracji wyszukiwania należy ponownie przeliczyć liczbę wyszukiwanych znaków.
// Sample for String::IndexOf(String, Int32, Int32)
using namespace System;
int main()
{
String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
String^ str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
int end;
int count;
end = str->Length;
start = end / 2;
Console::WriteLine();
Console::WriteLine( "All occurrences of 'he' from position {0} to {1}.", start, end - 1 );
Console::WriteLine( "{1}{0}{2}{0}{3}{0}", Environment::NewLine, br1, br2, str );
Console::Write( "The string 'he' occurs at position(s): " );
count = 0;
at = 0;
while ( (start <= end) && (at > -1) )
{
// start+count must be a position within -str-.
count = end - start;
at = str->IndexOf( "he", start, count );
if ( at == -1 )
break;
Console::Write( "{0} ", at );
start = at + 1;
}
Console::WriteLine();
}
/*
This example produces the following results:
All occurrences of 'he' from position 33 to 66.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 45 56
*/
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
*/
' 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
'
'
Uwagi
Numerowanie indeksu zaczyna się od 0 (zero). Parametr startIndex
może mieć wartość od 0 do długości wystąpienia ciągu.
Ta metoda przeprowadza wyszukiwanie wyrazów (wielkość liter i z uwzględnieniem ustawień kulturowych) przy użyciu bieżącej kultury. Wyszukiwanie rozpoczyna się od startIndex
i kontynuuje do startIndex
+ count
-1. Znak w startIndex
+ count
at nie jest uwzględniony w wyszukiwaniu.
Zestawy znaków zawierają znaki do pominięcia. Są to znaki nieuwzględniane podczas porównywania pod względem językowym lub z uwzględnieniem ustawień kulturowych. W wyszukiwaniu z rozróżnianą kulturą, jeśli zawiera znak ignorowany, wynik jest odpowiednikiem wyszukiwania z value
usuniętym znakiem. Jeśli składa się tylko z jednego lub większej liczby ignorowanych znaków, metoda zawsze zwraca wartość , czyli pozycję znaku, value
od której rozpoczyna się IndexOf(String, Int32, Int32) startIndex
wyszukiwanie. W poniższym przykładzie metoda służy do znalezienia pozycji łącznika programowego IndexOf(String, Int32, Int32) (U+00AD), po którym następuje znak "m", zaczynając od trzeciej do szóstej pozycji znaku w dwóch ciągach. Tylko jeden z ciągów zawiera wymagany podciąg. Jeśli przykład jest uruchamiany na .NET Framework 4 lub nowszym, w obu przypadkach, ponieważ łącznik nieciągły jest znakiem do zignorowania, metoda zwraca indeks "m" w ciągu podczas wykonywania porównania z rozróżnianą kulturą. Należy pamiętać, że w przypadku pierwszego ciągu, który zawiera łącznik nietrwały, a po nim „m”, metoda nie zwraca indeksu łącznika nietrwałego, ale zamiast tego zwraca indeks „m”.
using System;
public class Example
{
public static void Main()
{
string searchString = "\u00ADm";
string s1 = "ani\u00ADmal" ;
string s2 = "animal";
Console.WriteLine(s1.IndexOf(searchString, 2, 4));
Console.WriteLine(s2.IndexOf(searchString, 2, 4));
// The example displays the following output:
// 4
// 3
}
}
Module Example
Public Sub Main()
Dim searchString As String = Chrw(&h00AD) + "m"
Dim s1 As String = "ani" + ChrW(&h00AD) + "mal"
Dim s2 As String = "animal"
Console.WriteLine(s1.IndexOf(searchString, 2, 4))
Console.WriteLine(s2.IndexOf(searchString, 2, 4))
End Sub
End Module
' The example displays the following output:
' 4
' 3
Uwagi dotyczące wywoływania
Jak wyjaśniono w najlepsze rozwiązaniadotyczące używania ciągów , zalecamy unikanie wywoływania metod porównywania ciągów, które zastępują wartości domyślne, a zamiast tego wywołują metody, które wymagają jawnego ustawienia parametrów. Aby wykonać tę operację przy użyciu reguł porównania bieżącej kultury, wywołaj przeciążenie metody z IndexOf(String, Int32, Int32, StringComparison) CurrentCulture wartością comparisonType
parametru .
Zobacz też
Dotyczy
IndexOf(Char, StringComparison)
Raportuje indeks od zera pierwszego wystąpienia określonego znaku Unicode w tym ciągu. Parametr określa typ wyszukiwania dla określonego znaku.
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
Parametry
- value
- Char
Znak do szukania.
- comparisonType
- StringComparison
Wartość wyliczenia określająca reguły wyszukiwania.
Zwraca
Indeks od zera, value
jeśli ten znak zostanie znaleziony, lub -1, jeśli nie jest.
Wyjątki
comparisonType
nie jest prawidłową StringComparison wartością.
Uwagi
Indeks numerowania rozpoczyna się od zera.
Parametr jest członkiem wyliczenia, który określa, czy wyszukiwanie argumentu używa bieżącej lub niezmiennej kultury, jest rozróżniana wielkość liter lub wielkość liter, lub używa reguł porównania wyrazów lub comparisonType
StringComparison value
porządkowych.
Dotyczy
IndexOf(Char, Int32)
Raportuje indeks od zera pierwszego wystąpienia określonego znaku Unicode w tym ciągu. Wyszukiwanie rozpoczyna się od określonej pozycji znaku.
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
Parametry
- value
- Char
Znak Unicode do szukania.
- startIndex
- Int32
Pozycja rozpoczęcia wyszukiwania.
Zwraca
Pozycja indeksu od zera od początku ciągu, jeśli ten znak zostanie znaleziony, lub value
-1, jeśli nie jest.
Wyjątki
startIndex
jest mniejsza niż 0 (zero) lub większa niż długość ciągu.
Przykłady
W poniższym przykładzie pokazano IndexOf metodę .
// Sample for String::IndexOf(Char, Int32)
using namespace System;
int main()
{
String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
String^ str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
Console::WriteLine();
Console::WriteLine( "All occurrences of 't' from position 0 to {0}.", str->Length - 1 );
Console::WriteLine( "{1}{0}{2}{0}{3}{0}", Environment::NewLine, br1, br2, str );
Console::Write( "The letter 't' occurs at position(s): " );
at = 0;
start = 0;
while ( (start < str->Length) && (at > -1) )
{
at = str->IndexOf( 't', start );
if ( at == -1 )
break;
Console::Write( "{0} ", at );
start = at + 1;
}
Console::WriteLine();
}
/*
This example produces the following results:
All occurrences of 't' from position 0 to 66.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 7 11 33 41 44 55 64
*/
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
*/
' 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
'
'
Uwagi
Numerowanie indeksu zaczyna się od 0. Parametr startIndex
może mieć wartość od 0 do długości wystąpienia ciągu. Jeśli startIndex
jest równa długości wystąpienia ciągu, metoda zwraca wartość -1.
Wyszukiwanie obejmuje zakres startIndex
od do końca ciągu.
Ta metoda przeprowadza wyszukiwanie porządkowe (niewrażliwość na ustawienia kulturowe), gdzie znak jest uważany za równoważny innemu znakowi tylko wtedy, gdy ich wartości skalarne Unicode są takie same. Aby przeprowadzić wyszukiwanie zależne od kultury, użyj metody , w której wartość skalarna Unicode reprezentująca wstępnie skompilowany znak, taką jak "AE" (U+00C6), może być uważana za równoważną dowolnemu wystąpieniu składników znaku w prawidłowej sekwencji, takim jak CompareInfo.IndexOf "AE" (U+0041, U+0045), w zależności od kultury.
Zobacz też
Dotyczy
IndexOf(String)
Raportuje indeks od zera pierwszego wystąpienia określonego ciągu w tym wystąpieniu.
public:
int IndexOf(System::String ^ value);
public int IndexOf (string value);
member this.IndexOf : string -> int
Public Function IndexOf (value As String) As Integer
Parametry
- value
- String
Ciąg do wyszukania.
Zwraca
Pozycja indeksu od zera, jeśli ten ciąg zostanie znaleziony, lub value
-1, jeśli nie jest. Jeśli value
wartość to , Empty zwracana wartość to 0.
Wyjątki
value
to null
.
Przykłady
Poniższy przykład wyszukuje "n" w "zwierzę". Ponieważ indeksy ciągów zaczynają się od zera, a nie od jednego, metoda wskazuje, że IndexOf(String) "n" znajduje się na pozycji 1.
using namespace System;
void main()
{
String^ str = "animal";
String^ toFind = "n";
int index = str->IndexOf("n");
Console::WriteLine("Found '{0}' in '{1}' at position {2}",
toFind, str, index);
}
// The example displays the following output:
// Found 'n' in 'animal' at position 1
String str = "animal";
String toFind = "n";
int index = str.IndexOf("n");
Console.WriteLine("Found '{0}' in '{1}' at position {2}",
toFind, str, index);
// The example displays the following output:
// Found 'n' in 'animal' at position 1
Public Module Example
Public Sub Main()
Dim str As String = "animal"
Dim toFind As String = "n"
Dim index As Integer = str.IndexOf("n")
Console.WriteLine("Found '{0}' in '{1}' at position {2}",
toFind, str, index)
End Sub
End Module
' The example displays the following output:
' Found 'n' in 'animal' at position 1
W poniższym przykładzie użyto metody , aby określić pozycję początkową IndexOf nazwy zwierząt w zdaniu. Następnie używa tej pozycji, aby wstawić do zdania przymiotnik opisujący zwierzę.
using namespace System;
int main()
{
String^ animal1 = "fox";
String^ animal2 = "dog";
String^ strTarget = String::Format( "The {0} jumps over the {1}.", animal1, animal2 );
Console::WriteLine( "The original string is:{0}{1}{0}", Environment::NewLine, strTarget );
Console::Write( "Enter an adjective (or group of adjectives) to describe the {0}: ==> ", animal1 );
String^ adj1 = Console::ReadLine();
Console::Write( "Enter an adjective (or group of adjectives) to describe the {0}: ==> ", animal2 );
String^ adj2 = Console::ReadLine();
adj1 = String::Concat( adj1->Trim(), " " );
adj2 = String::Concat( adj2->Trim(), " " );
strTarget = strTarget->Insert( strTarget->IndexOf( animal1 ), adj1 );
strTarget = strTarget->Insert( strTarget->IndexOf( animal2 ), adj2 );
Console::WriteLine( " {0}The final string is: {0} {1}", Environment::NewLine, strTarget );
}
// Output from the example might appear as follows:
// The original string is:
// The fox jumps over the dog.
//
// Enter an adjective (or group of adjectives) to describe the fox: ==> bold
// Enter an adjective (or group of adjectives) to describe the dog: ==> lazy
//
// The final string is:
// The bold fox jumps over the lazy dog.
using System;
public class Example {
public static void Main()
{
string animal1 = "fox";
string animal2 = "dog";
string strTarget = String.Format("The {0} jumps over the {1}.",
animal1, animal2);
Console.WriteLine("The original string is:{0}{1}{0}",
Environment.NewLine, strTarget);
Console.Write("Enter an adjective (or group of adjectives) " +
"to describe the {0}: ==> ", animal1);
string adj1 = Console.ReadLine();
Console.Write("Enter an adjective (or group of adjectives) " +
"to describe the {0}: ==> ", animal2);
string adj2 = Console.ReadLine();
adj1 = adj1.Trim() + " ";
adj2 = adj2.Trim() + " ";
strTarget = strTarget.Insert(strTarget.IndexOf(animal1), adj1);
strTarget = strTarget.Insert(strTarget.IndexOf(animal2), adj2);
Console.WriteLine("{0}The final string is:{0}{1}",
Environment.NewLine, strTarget);
}
}
// Output from the example might appear as follows:
// The original string is:
// The fox jumps over the dog.
//
// Enter an adjective (or group of adjectives) to describe the fox: ==> bold
// Enter an adjective (or group of adjectives) to describe the dog: ==> lazy
//
// The final string is:
// The bold fox jumps over the lazy dog.
Public Class Example
Public Shared Sub Main()
Dim animal1 As String = "fox"
Dim animal2 As String = "dog"
Dim strTarget As String = String.Format("The {0} jumps over the {1}.",
animal1, animal2)
Console.WriteLine("The original string is: {0}{1}{0}",
Environment.NewLine, strTarget)
Console.Write("Enter an adjective (or group of adjectives) " +
"to describe the {0}: ==> ", animal1)
Dim adj1 As String = Console.ReadLine()
Console.Write("Enter an adjective (or group of adjectives) " +
"to describe the {0}: ==> ", animal2)
Dim adj2 As String = Console.ReadLine()
adj1 = adj1.Trim() + " "
adj2 = adj2.Trim() + " "
strTarget = strTarget.Insert(strTarget.IndexOf(animal1), adj1)
strTarget = strTarget.Insert(strTarget.IndexOf(animal2), adj2)
Console.WriteLine("{0}The final string is:{0}{1}",
Environment.NewLine, strTarget)
End Sub
End Class
' Output from the example might appear as follows:
' The original string is:
' The fox jumps over the dog.
'
' Enter an adjective (or group of adjectives) to describe the fox: ==> bold
' Enter an adjective (or group of adjectives) to describe the dog: ==> lazy
'
' The final string is:
' The bold fox jumps over the lazy dog.
Uwagi
Indeks numerowania rozpoczyna się od zera.
Ta metoda przeprowadza wyszukiwanie wyrazów (wielkość liter i z uwzględnieniem ustawień kulturowych) przy użyciu bieżącej kultury. Wyszukiwanie rozpoczyna się od pierwszej pozycji znaku w tym wystąpieniu i jest kontynuowane do ostatniej pozycji znaku.
Zestawy znaków zawierają znaki do pominięcia. Są to znaki nieuwzględniane podczas porównywania pod względem językowym lub z uwzględnieniem ustawień kulturowych. W wyszukiwaniu z rozróżnianą kulturą, jeśli zawiera znak ignorowany, wynik jest odpowiednikiem wyszukiwania z value
usuniętym znakiem. Jeśli składa się tylko z jednego lub większej liczby ignorowanych znaków, metoda zawsze zwraca value
wartość 0 (zero), aby wskazać, że dopasowanie znajduje się na IndexOf(String) początku bieżącego wystąpienia. W poniższym przykładzie metoda jest używana do znalezienia trzech podciągów (łącznika programowego (U+00AD), łącznika programowego, po którym następuje "n" i łącznika programowego, po którym następuje "m") w dwóch IndexOf(String) ciągach. Tylko jeden z ciągów zawiera łącznik nietrwały. Jeśli przykład jest uruchamiany na .NET Framework 4 lub nowszym, w każdym przypadku, ponieważ łącznik nieimigrowalny jest znakiem do zignorowania, wynik jest taki sam, jak gdyby łącznik nie został uwzględniony w value
. Podczas wyszukiwania tylko łącznika programowego metoda zwraca wartość 0 (zero), aby wskazać, że znaleziono dopasowanie na początku ciągu.
using System;
public class Example
{
public static void Main()
{
string s1 = "ani\u00ADmal";
string s2 = "animal";
// Find the index of the soft hyphen.
Console.WriteLine(s1.IndexOf("\u00AD"));
Console.WriteLine(s2.IndexOf("\u00AD"));
// Find the index of the soft hyphen followed by "n".
Console.WriteLine(s1.IndexOf("\u00ADn"));
Console.WriteLine(s2.IndexOf("\u00ADn"));
// Find the index of the soft hyphen followed by "m".
Console.WriteLine(s1.IndexOf("\u00ADm"));
Console.WriteLine(s2.IndexOf("\u00ADm"));
// The example displays the following output
// if run under the .NET Framework 4 or later:
// 0
// 0
// 1
// 1
// 4
// 3
}
}
Module Example
Public Sub Main()
Dim softHyphen As String = ChrW(&h00AD)
Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"
' Find the index of the soft hyphen.
Console.WriteLine(s1.IndexOf(softHyphen))
Console.WriteLine(s2.IndexOf(softHyphen))
' Find the index of the soft hyphen followed by "n".
Console.WriteLine(s1.IndexOf(softHyphen + "n"))
Console.WriteLine(s2.IndexOf(softHyphen + "n"))
' Find the index of the soft hyphen followed by "m".
Console.WriteLine(s1.IndexOf(softHyphen + "m"))
Console.WriteLine(s2.IndexOf(softHyphen + "m"))
End Sub
End Module
' The example displays the following output
' if run under the .NET Framework 4 or later:
' 0
' 0
' 1
' 1
' 4
' 3
Uwagi dotyczące wywoływania
Jak wyjaśniono w najlepsze rozwiązaniadotyczące używania ciągów , zalecamy unikanie wywoływania metod porównywania ciągów, które zastępują wartości domyślne, a zamiast tego wywołują metody, które wymagają jawnego ustawienia parametrów. Aby znaleźć pierwszy indeks podciągu w wystąpieniu ciągu przy użyciu reguł porównania bieżącej kultury, wywołaj przeciążenie metody z wartością IndexOf(String, StringComparison) CurrentCulture comparisonType
parametru .
Zobacz też
Dotyczy
IndexOf(Char)
Raportuje indeks od zera pierwszego wystąpienia określonego znaku Unicode w tym ciągu.
public:
int IndexOf(char value);
public int IndexOf (char value);
member this.IndexOf : char -> int
Public Function IndexOf (value As Char) As Integer
Parametry
- value
- Char
Znak Unicode do szukania.
Zwraca
Pozycja indeksu od zera, jeśli ten znak zostanie znaleziony, lub value
-1, jeśli nie jest.
Przykłady
W poniższym przykładzie pokazano, jak można wyszukać znak String przy użyciu IndexOf metody .
using namespace System;
void main()
{
// Create a Unicode String with 5 Greek Alpha characters.
String^ szGreekAlpha = gcnew String(L'\x0391',5);
// Create a Unicode String with a 3 Greek Omega characters.
String^ szGreekOmega = L"\x03A9\x03A9\x03A9";
String^ szGreekLetters = String::Concat(szGreekOmega, szGreekAlpha,
szGreekOmega->Clone());
// Display the entire string.
Console::WriteLine(szGreekLetters);
// The first index of Alpha.
int ialpha = szGreekLetters->IndexOf( L'\x0391');
// The first index of Omega.
int iomega = szGreekLetters->IndexOf(L'\x03A9');
Console::WriteLine("First occurrence of the Greek letter Alpha: Index {0}",
ialpha);
Console::WriteLine("First occurrence of the Greek letter Omega: Index {0}",
iomega);
}
// The example displays the following output:
// The string: OOO?????OOO
// First occurrence of the Greek letter Alpha: Index 3
// First occurrence of the Greek letter Omega: Index 0
// 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
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
Uwagi
Indeks numerowania rozpoczyna się od zera.
Ta metoda przeprowadza wyszukiwanie porządkowe (niewrażliwość na ustawienia kulturowe), gdzie znak jest uważany za równoważny innemu znakowi tylko wtedy, gdy ich wartości skalarne Unicode są takie same. Aby przeprowadzić wyszukiwanie zależne od kultury, użyj metody , w której wartość skalarna Unicode reprezentująca wstępnie skompilowany znak, taką jak "AE" (U+00C6), może być uważana za równoważną dowolnemu wystąpieniu składników znaku w prawidłowej sekwencji, takim jak CompareInfo.IndexOf "AE" (U+0041, U+0045), w zależności od kultury.
Zobacz też
Dotyczy
IndexOf(String, Int32)
Raportuje indeks od zera pierwszego wystąpienia określonego ciągu w tym wystąpieniu. Wyszukiwanie rozpoczyna się od określonej pozycji znaku.
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
Parametry
- value
- String
Ciąg do wyszukania.
- startIndex
- Int32
Pozycja rozpoczęcia wyszukiwania.
Zwraca
Pozycja indeksu od zera od początku bieżącego wystąpienia, jeśli ten ciąg zostanie znaleziony, lub value
-1, jeśli nie jest. Jeśli value
wartość to , Empty zwracana wartość to startIndex
.
Wyjątki
value
to null
.
startIndex
jest mniejsza niż 0 (zero) lub większa niż długość tego ciągu.
Przykłady
Poniższy przykład wyszukuje wszystkie wystąpienia określonego ciągu w ciągu docelowym.
using namespace System;
int main()
{
String^ strSource = "This is the string which we will perform the search on";
Console::WriteLine( "The search string is: {0}\"{1}\" {0}", Environment::NewLine, strSource );
String^ strTarget = "";
int found = 0;
int totFinds = 0;
do
{
Console::Write( "Please enter a search value to look for in the above string (hit Enter to exit) ==> " );
strTarget = Console::ReadLine();
if ( !strTarget->Equals( "" ) )
{
for ( int i = 0; i < strSource->Length; i++ )
{
found = strSource->IndexOf( strTarget, i );
if (found >= 0)
{
totFinds++;
i = found;
}
else
break;
}
}
else
return 0;
Console::WriteLine( "{0}The search parameter '{1}' was found {2} times. {0}", Environment::NewLine, strTarget, totFinds );
totFinds = 0;
}
while ( true );
}
using System;
public class IndexOfTest {
public static void Main() {
string strSource = "This is the string which we will perform the search on";
Console.WriteLine("The search string is:{0}\"{1}\"{0}", Environment.NewLine, strSource);
string strTarget = "";
int found = 0;
int totFinds = 0;
do {
Console.Write("Please enter a search value to look for in the above string (hit Enter to exit) ==> ");
strTarget = Console.ReadLine();
if (strTarget != "") {
for (int i = 0; i < strSource.Length; i++) {
found = strSource.IndexOf(strTarget, i);
if (found >= 0) {
totFinds++;
i = found;
}
else
{
break;
}
}
}
else
{
return;
}
Console.WriteLine("{0}The search parameter '{1}' was found {2} times.{0}",
Environment.NewLine, strTarget, totFinds);
totFinds = 0;
} while ( true );
}
}
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
Uwagi
Numerowanie indeksu zaczyna się od 0. Parametr startIndex
może mieć wartość od 0 do długości wystąpienia ciągu. Jeśli startIndex
jest równa długości wystąpienia ciągu, metoda zwraca wartość -1.
Ta metoda przeprowadza wyszukiwanie wyrazów (wielkość liter i z uwzględnieniem ustawień kulturowych) przy użyciu bieżącej kultury. Wyszukiwanie rozpoczyna się od pozycji znaku w tym wystąpieniu i startIndex
jest kontynuowane do ostatniej pozycji znaku.
Zestawy znaków zawierają znaki do pominięcia. Są to znaki nieuwzględniane podczas porównywania pod względem językowym lub z uwzględnieniem ustawień kulturowych. W wyszukiwaniu z rozróżnianą kulturą, jeśli zawiera znak ignorowany, wynik jest odpowiednikiem wyszukiwania z value
usuniętym znakiem. Jeśli składa się tylko z jednego lub większej liczby ignorowanych znaków, metoda zawsze zwraca wartość , czyli pozycję znaku, value
od której rozpoczyna się IndexOf(String, Int32) startIndex
wyszukiwanie. W poniższym przykładzie metoda służy do znalezienia pozycji łącznika programowego IndexOf(String, Int32) (U+00AD), po którym następuje "m" w dwóch ciągach. Tylko jeden z ciągów zawiera wymagany podciąg. Jeśli przykład jest uruchamiany na .NET Framework 4 lub nowszym, w obu przypadkach, ponieważ łącznik nieciągły jest znakiem do zignorowania, metoda zwraca indeks "m" w ciągu. Należy pamiętać, że w przypadku pierwszego ciągu, który zawiera łącznik nietrwały, a po nim „m”, metoda nie zwraca indeksu łącznika nietrwałego, ale zamiast tego zwraca indeks „m”.
using System;
public class Example
{
public static void Main()
{
string searchString = "\u00ADm";
string s1 = "ani\u00ADmal" ;
string s2 = "animal";
Console.WriteLine(s1.IndexOf(searchString, 2));
Console.WriteLine(s2.IndexOf(searchString, 2));
// The example displays the following output:
// 4
// 3
}
}
Module Example
Public Sub Main()
Dim searchString As String = Chrw(&h00AD) + "m"
Dim s1 As String = "ani" + ChrW(&h00AD) + "mal"
Dim s2 As String = "animal"
Console.WriteLine(s1.IndexOf(searchString, 2))
Console.WriteLine(s2.IndexOf(searchString, 2))
End Sub
End Module
' The example displays the following output:
' 4
' 3
Uwagi dotyczące wywoływania
Jak wyjaśniono w najlepsze rozwiązaniadotyczące używania ciągów , zalecamy unikanie wywoływania metod porównywania ciągów, które zastępują wartości domyślne, a zamiast tego wywołują metody, które wymagają jawnego ustawienia parametrów. Aby znaleźć pierwszy indeks podciągu, który występuje po określonej pozycji znaku przy użyciu reguł porównania bieżącej kultury, wywołaj przeciążenie metody z wartością IndexOf(String, Int32, StringComparison) CurrentCulture comparisonType
parametru .