String.LastIndexOf Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Сообщает о позиции индекса от нуля последнего вхождения указанного символа Юникода или строки в этом экземпляре. Метод возвращает -1, если символ или строка не найдена в этом экземпляре.
Перегрузки
| Имя | Описание |
|---|---|
| LastIndexOf(String, Int32, Int32, StringComparison) |
Сообщает о позиции индекса от нуля последнего вхождения указанной строки в этом экземпляре. Поиск начинается с указанной позиции символа и переходит к началу строки для указанного количества позиций символов. Параметр задает тип сравнения, выполняемого при поиске указанной строки. |
| LastIndexOf(Char, Int32, Int32, StringComparison) | |
| LastIndexOf(Rune, Int32, StringComparison) | |
| LastIndexOf(Rune, Int32, Int32) | |
| LastIndexOf(String, Int32, StringComparison) |
Сообщает отсчитываемый от нуля индекс последнего вхождения указанной строки в текущем String объекте. Поиск начинается с указанной позиции символа и продолжается назад к началу строки. Параметр задает тип сравнения, выполняемого при поиске указанной строки. |
| LastIndexOf(String, Int32, Int32) |
Сообщает о позиции индекса от нуля последнего вхождения указанной строки в этом экземпляре. Поиск начинается с указанной позиции символа и переходит к началу строки для указанного числа позиций символов. |
| LastIndexOf(Char, Int32, StringComparison) | |
| LastIndexOf(Char, Int32, Int32) |
Сообщает отсчитывает отсчитываемое от нуля положение индекса последнего вхождения указанного символа Юникода в подстроке в этом экземпляре. Поиск начинается с указанной позиции символа и переходит к началу строки для указанного числа позиций символов. |
| LastIndexOf(String, Int32) |
Сообщает о позиции индекса от нуля последнего вхождения указанной строки в этом экземпляре. Поиск начинается с указанной позиции символа и продолжается назад к началу строки. |
| LastIndexOf(Rune, Int32) | |
| LastIndexOf(String, StringComparison) |
Сообщает отсчитываемый от нуля индекс последнего вхождения указанной строки в текущем String объекте. Параметр указывает тип поиска, используемый для указанной строки. |
| LastIndexOf(Rune, Int32, Int32, StringComparison) | |
| LastIndexOf(Char, StringComparison) | |
| LastIndexOf(Char, Int32) |
Сообщает о позиции индекса от нуля последнего вхождения указанного символа Юникода в этом экземпляре. Поиск начинается с указанной позиции символа и продолжается назад к началу строки. |
| LastIndexOf(Rune) | |
| LastIndexOf(String) |
Сообщает о позиции индекса от нуля последнего вхождения указанной строки в этом экземпляре. |
| LastIndexOf(Char) |
Сообщает о позиции индекса от нуля последнего вхождения указанного символа Юникода в этом экземпляре. |
| LastIndexOf(Rune, StringComparison) |
LastIndexOf(String, Int32, Int32, StringComparison)
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
Сообщает о позиции индекса от нуля последнего вхождения указанной строки в этом экземпляре. Поиск начинается с указанной позиции символа и переходит к началу строки для указанного количества позиций символов. Параметр задает тип сравнения, выполняемого при поиске указанной строки.
public:
int LastIndexOf(System::String ^ value, int startIndex, int count, StringComparison comparisonType);
public int LastIndexOf(string value, int startIndex, int count, StringComparison comparisonType);
member this.LastIndexOf : string * int * int * StringComparison -> int
Public Function LastIndexOf (value As String, startIndex As Integer, count As Integer, comparisonType As StringComparison) As Integer
Параметры
- value
- String
Строка для поиска.
- startIndex
- Int32
Начальная позиция поиска. Поиск начинается с startIndex начала этого экземпляра.
- count
- Int32
Число проверяемых позиций символов.
- comparisonType
- StringComparison
Одно из значений перечисления, указывающее правила поиска.
Возвращаемое значение
Отсчитываемое от нуля положение начального value индекса параметра, если эта строка найдена, или -1, если он не найден или равен текущему экземпляру Empty.
Исключения
value равно null.
count является отрицательным.
-или-
Текущий экземпляр не равен Emptyи startIndex является отрицательным.
-или-
Текущий экземпляр не равен Emptyи startIndex больше длины этого экземпляра.
-или-
Текущий экземпляр не равен Emptyи startIndex + 1 — count указывает позицию, которая не находится в этом экземпляре.
-или-
Текущий экземпляр равен Empty и startIndex меньше -1 или больше нуля.
-или-
Текущий экземпляр равен Empty и count больше 1.
comparisonType недопустимое StringComparison значение.
Примеры
В следующем примере показаны три перегрузки LastIndexOf метода, которые находят последнее вхождение строки в другой строке с использованием различных значений перечисления StringComparison .
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
using System;
using System.Threading;
using System.Globalization;
class Sample
{
public static void Main()
{
string intro = "Find the last occurrence of a character using different " +
"values of StringComparison.";
string resultFmt = "Comparison: {0,-28} Location: {1,3}";
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
string CapitalAWithRing = "\u00c5";
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
string cat = "A Cheshire c" + "\u0061\u030a" + "t";
int loc = 0;
StringComparison[] scValues = {
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
StringComparison.OrdinalIgnoreCase };
// Clear the screen and display an introduction.
Console.Clear();
Console.WriteLine(intro);
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("The current culture is \"{0}\" - {1}.",
Thread.CurrentThread.CurrentCulture.Name,
Thread.CurrentThread.CurrentCulture.DisplayName);
// Display the string to search for and the string to search.
Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"",
CapitalAWithRing, cat);
Console.WriteLine();
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
Console.WriteLine("Part 1: Start index and count are specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion. Specify the
// start index.
Console.WriteLine("\nPart 2: Start index is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, sc);
Console.WriteLine(resultFmt, sc, loc);
}
}
}
/*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*/
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
open System
open System.Threading
open System.Globalization
let intro = "Find the last occurrence of a character using different values of StringComparison."
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let CapitalAWithRing = "\u00c5"
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues =
[| StringComparison.CurrentCulture
StringComparison.CurrentCultureIgnoreCase
StringComparison.InvariantCulture
StringComparison.InvariantCultureIgnoreCase
StringComparison.Ordinal
StringComparison.OrdinalIgnoreCase |]
// Clear the screen and display an introduction.
Console.Clear()
printfn $"{intro}"
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."
// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
printfn "Part 1: Start index and count are specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*)
' This code example demonstrates the
' System.String.LastIndexOf(String, ..., StringComparison) methods.
Imports System.Threading
Imports System.Globalization
Class Sample
Public Shared Sub Main()
Dim intro As String = "Find the last occurrence of a character using different " & _
"values of StringComparison."
Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
' Define a string to search for.
' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
Dim CapitalAWithRing As String = "Å"
' Define a string to search.
' The result of combining the characters LATIN SMALL LETTER A and COMBINING
' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
Dim cat As String = "A Cheshire c" & "å" & "t"
Dim loc As Integer = 0
Dim scValues As StringComparison() = { _
StringComparison.CurrentCulture, _
StringComparison.CurrentCultureIgnoreCase, _
StringComparison.InvariantCulture, _
StringComparison.InvariantCultureIgnoreCase, _
StringComparison.Ordinal, _
StringComparison.OrdinalIgnoreCase }
Dim sc As StringComparison
' Clear the screen and display an introduction.
Console.Clear()
Console.WriteLine(intro)
' Display the current culture because culture affects the result. For example,
' try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
Console.WriteLine("The current culture is ""{0}"" - {1}.", _
Thread.CurrentThread.CurrentCulture.Name, _
Thread.CurrentThread.CurrentCulture.DisplayName)
' Display the string to search for and the string to search.
Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
CapitalAWithRing, cat)
Console.WriteLine()
' Note that in each of the following searches, we look for
' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
' the string was not found.
' Search using different values of StringComparsion. Specify the start
' index and count.
Console.WriteLine("Part 1: Start index and count are specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion. Specify the
' start index.
Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion.
Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
End Sub
End Class
'
'Note: This code example was executed on a console whose user interface
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the last occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
Комментарии
Нумерация индексов начинается с нуля. То есть первый символ в строке равен нулю индекса, а последний — Length 1.
Поиск начинается с startIndex позиции символа и продолжается назад до тех пор, пока value не будет найдено или count будет проверено положение символов. Например, если startIndex значение равно Length - 1, метод выполняет поиск обратных count символов из последнего символа в строке.
Параметр comparisonType указывает для поиска value параметра с помощью:
- Текущий или инвариантный язык и региональные параметры.
- Поиск без учета регистра или регистра.
- Правила сравнения слов или порядкового номера.
Примечания для тех, кто вызывает этот метод
Наборы символов включают игнорируемые символы, которые не учитываются при выполнении лингвистического или языка и региональных параметров. В поиске с учетом языка и региональных параметров (т comparisonTypeOrdinalOrdinalIgnoreCase. е. в противном случае), если value он содержит игнорируемый символ, результат эквивалентен поиску с удаленным символом.
В следующем примере LastIndexOf(String, Int32, Int32, StringComparison) метод используется для поиска позиции мягкого дефиса (U+00AD), за которым следует "m" во всех, кроме первой позиции символа до окончательного "m" в двух строках. Только одна из строк содержит необходимую подстроку. Если пример выполняется в .NET Framework 4 или более поздней версии, в обоих случаях, так как мягкий дефис является игнорируемым символом, метод возвращает индекс "m" в строке при выполнении сравнения с учетом языка и региональных параметров. Однако при выполнении порядкового сравнения она находит подстроку только в первой строке. Обратите внимание, что в случае первой строки, которая включает мягкий дефис, за которым следует "m", метод возвращает индекс "m" при выполнении сравнения с учетом языка и региональных параметров. Метод возвращает индекс мягкого дефиса в первой строке только при выполнении порядкового сравнения.
string searchString = "\u00ADm";
string s1 = "ani\u00ADmal";
string s2 = "animal";
int position;
position = s1.LastIndexOf('m');
if (position >= 1)
{
Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture));
Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.Ordinal));
}
position = s2.LastIndexOf('m');
if (position >= 1)
{
Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture));
Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.Ordinal));
}
// The example displays the following output:
//
// 4
// 3
// 3
// -1
let searchString = "\u00ADm"
let s1 = "ani\u00ADmal"
let s2 = "animal"
let position = s1.LastIndexOf 'm'
if position >= 1 then
printfn $"{s1.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture)}"
printfn $"{s1.LastIndexOf(searchString, position, position, StringComparison.Ordinal)}"
let position = s2.LastIndexOf 'm'
if position >= 1 then
printfn $"{s2.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture)}"
printfn $"{s2.LastIndexOf(searchString, position, position, StringComparison.Ordinal)}"
// The example displays the following output:
//
// 4
// 3
// 3
// -1
Dim searchString As String = ChrW(&HAD) + "m"
Dim s1 As String = "ani" + ChrW(&HAD) + "m"
Dim s2 As String = "animal"
Dim position As Integer
position = s1.LastIndexOf("m"c)
If position >= 1 Then
Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture))
Console.WriteLine(s1.LastIndexOf(searchString, position, position, StringComparison.Ordinal))
End If
position = s2.LastIndexOf("m"c)
If position >= 1 Then
Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.CurrentCulture))
Console.WriteLine(s2.LastIndexOf(searchString, position, position, StringComparison.Ordinal))
End If
' The example displays the following output:
'
' 4
' 3
' 3
' -1
Применяется к
LastIndexOf(Char, Int32, Int32, StringComparison)
public:
int LastIndexOf(char value, int startIndex, int count, StringComparison comparisonType);
public int LastIndexOf(char value, int startIndex, int count, StringComparison comparisonType);
member this.LastIndexOf : char * int * int * StringComparison -> int
Public Function LastIndexOf (value As Char, startIndex As Integer, count As Integer, comparisonType As StringComparison) As Integer
Параметры
- value
- Char
- startIndex
- Int32
- count
- Int32
- comparisonType
- StringComparison
Возвращаемое значение
Применяется к
LastIndexOf(Rune, Int32, StringComparison)
public:
int LastIndexOf(System::Text::Rune value, int startIndex, StringComparison comparisonType);
public int LastIndexOf(System.Text.Rune value, int startIndex, StringComparison comparisonType);
member this.LastIndexOf : System.Text.Rune * int * StringComparison -> int
Public Function LastIndexOf (value As Rune, startIndex As Integer, comparisonType As StringComparison) As Integer
Параметры
- value
- Rune
- startIndex
- Int32
- comparisonType
- StringComparison
Возвращаемое значение
Применяется к
LastIndexOf(Rune, Int32, Int32)
public:
int LastIndexOf(System::Text::Rune value, int startIndex, int count);
public int LastIndexOf(System.Text.Rune value, int startIndex, int count);
member this.LastIndexOf : System.Text.Rune * int * int -> int
Public Function LastIndexOf (value As Rune, startIndex As Integer, count As Integer) As Integer
Параметры
- value
- Rune
- startIndex
- Int32
- count
- Int32
Возвращаемое значение
Применяется к
LastIndexOf(String, Int32, StringComparison)
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
Сообщает отсчитываемый от нуля индекс последнего вхождения указанной строки в текущем String объекте. Поиск начинается с указанной позиции символа и продолжается назад к началу строки. Параметр задает тип сравнения, выполняемого при поиске указанной строки.
public:
int LastIndexOf(System::String ^ value, int startIndex, StringComparison comparisonType);
public int LastIndexOf(string value, int startIndex, StringComparison comparisonType);
member this.LastIndexOf : string * int * StringComparison -> int
Public Function LastIndexOf (value As String, startIndex As Integer, comparisonType As StringComparison) As Integer
Параметры
- value
- String
Строка для поиска.
- startIndex
- Int32
Начальная позиция поиска. Поиск начинается с startIndex начала этого экземпляра.
- comparisonType
- StringComparison
Одно из значений перечисления, указывающее правила поиска.
Возвращаемое значение
Отсчитываемое от нуля положение начального value индекса параметра, если эта строка найдена, или -1, если он не найден или равен текущему экземпляру Empty.
Исключения
value равно null.
Текущий экземпляр не равен EmptystartIndex нулю или больше длины текущего экземпляра.
-или-
Текущий экземпляр равен EmptystartIndex и меньше -1 или больше нуля.
comparisonType недопустимое StringComparison значение.
Примеры
В следующем примере показаны три перегрузки LastIndexOf метода, которые находят последнее вхождение строки в другой строке с использованием различных значений перечисления StringComparison .
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
using System;
using System.Threading;
using System.Globalization;
class Sample
{
public static void Main()
{
string intro = "Find the last occurrence of a character using different " +
"values of StringComparison.";
string resultFmt = "Comparison: {0,-28} Location: {1,3}";
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
string CapitalAWithRing = "\u00c5";
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
string cat = "A Cheshire c" + "\u0061\u030a" + "t";
int loc = 0;
StringComparison[] scValues = {
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
StringComparison.OrdinalIgnoreCase };
// Clear the screen and display an introduction.
Console.Clear();
Console.WriteLine(intro);
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("The current culture is \"{0}\" - {1}.",
Thread.CurrentThread.CurrentCulture.Name,
Thread.CurrentThread.CurrentCulture.DisplayName);
// Display the string to search for and the string to search.
Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"",
CapitalAWithRing, cat);
Console.WriteLine();
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
Console.WriteLine("Part 1: Start index and count are specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion. Specify the
// start index.
Console.WriteLine("\nPart 2: Start index is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, sc);
Console.WriteLine(resultFmt, sc, loc);
}
}
}
/*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*/
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
open System
open System.Threading
open System.Globalization
let intro = "Find the last occurrence of a character using different values of StringComparison."
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let CapitalAWithRing = "\u00c5"
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues =
[| StringComparison.CurrentCulture
StringComparison.CurrentCultureIgnoreCase
StringComparison.InvariantCulture
StringComparison.InvariantCultureIgnoreCase
StringComparison.Ordinal
StringComparison.OrdinalIgnoreCase |]
// Clear the screen and display an introduction.
Console.Clear()
printfn $"{intro}"
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."
// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
printfn "Part 1: Start index and count are specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*)
' This code example demonstrates the
' System.String.LastIndexOf(String, ..., StringComparison) methods.
Imports System.Threading
Imports System.Globalization
Class Sample
Public Shared Sub Main()
Dim intro As String = "Find the last occurrence of a character using different " & _
"values of StringComparison."
Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
' Define a string to search for.
' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
Dim CapitalAWithRing As String = "Å"
' Define a string to search.
' The result of combining the characters LATIN SMALL LETTER A and COMBINING
' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
Dim cat As String = "A Cheshire c" & "å" & "t"
Dim loc As Integer = 0
Dim scValues As StringComparison() = { _
StringComparison.CurrentCulture, _
StringComparison.CurrentCultureIgnoreCase, _
StringComparison.InvariantCulture, _
StringComparison.InvariantCultureIgnoreCase, _
StringComparison.Ordinal, _
StringComparison.OrdinalIgnoreCase }
Dim sc As StringComparison
' Clear the screen and display an introduction.
Console.Clear()
Console.WriteLine(intro)
' Display the current culture because culture affects the result. For example,
' try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
Console.WriteLine("The current culture is ""{0}"" - {1}.", _
Thread.CurrentThread.CurrentCulture.Name, _
Thread.CurrentThread.CurrentCulture.DisplayName)
' Display the string to search for and the string to search.
Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
CapitalAWithRing, cat)
Console.WriteLine()
' Note that in each of the following searches, we look for
' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
' the string was not found.
' Search using different values of StringComparsion. Specify the start
' index and count.
Console.WriteLine("Part 1: Start index and count are specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion. Specify the
' start index.
Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion.
Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
End Sub
End Class
'
'Note: This code example was executed on a console whose user interface
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the last occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
Комментарии
Нумерация индексов начинается с нуля. То есть первый символ в строке равен нулю индекса, а последний — Length 1.
Поиск начинается с startIndex позиции символа и продолжается назад до тех пор, пока не value будет найдена или первая позиция символа была проверена. Например, если startIndex значение равно Length - 1, метод выполняет поиск каждого символа от последнего символа в строке до начала.
Параметр comparisonType задает поиск value параметра с использованием текущего или инвариантного языка и региональных параметров, используя нечувствительный к регистру или регистр нечувствительный поиск, а также использование правил сравнения слов или порядковых значений.
Примечания для тех, кто вызывает этот метод
Наборы символов включают игнорируемые символы, которые не учитываются при выполнении лингвистического или языка и региональных параметров. В поиске с учетом языка и региональных параметров (т comparisonTypeOrdinalOrdinalIgnoreCase. е. в противном случае), если value он содержит игнорируемый символ, результат эквивалентен поиску с удаленным символом.
В следующем примере метод используется для поиска позиции мягкого дефиса (U+00AD), за которым следует "m", LastIndexOf(String, Int32, StringComparison) начиная с окончательного "m" в двух строках. Только одна из строк содержит необходимую подстроку. Если пример выполняется в .NET Framework 4 или более поздней версии, в обоих случаях, так как мягкий дефис является игнорируемым символом, метод возвращает индекс "m" в строке при выполнении сравнения с учетом языка и региональных параметров. Обратите внимание, что в случае первой строки, которая включает мягкий дефис, за которым следует "m", метод возвращает индекс "m", а не индекс мягкого дефиса. Метод возвращает индекс мягкого дефиса в первой строке только при выполнении порядкового сравнения.
string searchString = "\u00ADm";
string s1 = "ani\u00ADmal";
string s2 = "animal";
int position;
position = s1.LastIndexOf('m');
if (position >= 0)
{
Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.CurrentCulture));
Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.Ordinal));
}
position = s2.LastIndexOf('m');
if (position >= 0)
{
Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.CurrentCulture));
Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.Ordinal));
}
// The example displays the following output:
//
// 4
// 3
// 3
// -1
let searchString = "\u00ADm"
let s1 = "ani\u00ADmal"
let s2 = "animal"
let position = s1.LastIndexOf 'm'
if position >= 0 then
printfn $"{s1.LastIndexOf(searchString, position, StringComparison.CurrentCulture)}"
printfn $"{s1.LastIndexOf(searchString, position, StringComparison.Ordinal)}"
let position = s2.LastIndexOf 'm'
if position >= 0 then
printfn $"{s2.LastIndexOf(searchString, position, StringComparison.CurrentCulture)}"
printfn $"{s2.LastIndexOf(searchString, position, StringComparison.Ordinal)}"
// The example displays the following output:
//
// 4
// 3
// 3
// -1
Dim searchString As String = ChrW(&HAD) + "m"
Dim s1 As String = "ani" + ChrW(&HAD) + "mal"
Dim s2 As String = "animal"
Dim position As Integer
position = s1.LastIndexOf("m"c)
If position >= 0 Then
Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.CurrentCulture))
Console.WriteLine(s1.LastIndexOf(searchString, position, StringComparison.Ordinal))
End If
position = s2.LastIndexOf("m"c)
If position >= 0 Then
Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.CurrentCulture))
Console.WriteLine(s2.LastIndexOf(searchString, position, StringComparison.Ordinal))
End If
' The example displays the following output:
'
' 4
' 3
' 3
' -1
Применяется к
LastIndexOf(String, Int32, Int32)
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
Сообщает о позиции индекса от нуля последнего вхождения указанной строки в этом экземпляре. Поиск начинается с указанной позиции символа и переходит к началу строки для указанного числа позиций символов.
public:
int LastIndexOf(System::String ^ value, int startIndex, int count);
public int LastIndexOf(string value, int startIndex, int count);
member this.LastIndexOf : string * int * int -> int
Public Function LastIndexOf (value As String, startIndex As Integer, count As Integer) As Integer
Параметры
- value
- String
Строка для поиска.
- startIndex
- Int32
Начальная позиция поиска. Поиск начинается с startIndex начала этого экземпляра.
- count
- Int32
Число проверяемых позиций символов.
Возвращаемое значение
Отсчитываемое от нуля положение value начального индекса, если эта строка найдена, или -1, если она не найдена или если текущий экземпляр равен Empty.
Исключения
value равно null.
count является отрицательным.
-или-
Текущий экземпляр не равен Emptyи startIndex является отрицательным.
-или-
Текущий экземпляр не равен Emptyи startIndex больше длины этого экземпляра.
-или-
Текущий экземпляр не равен Emptyи startIndex - count+ 1 указывает положение, которое не находится в этом экземпляре.
-или-
Текущий экземпляр равен Empty и startIndex меньше -1 или больше нуля.
-или-
Текущий экземпляр равен Empty и count больше 1.
Примеры
В следующем примере индекс всех вхождения строки в подстроке, работающей с конца подстроки до начала подстроки.
// Sample for String.LastIndexOf(String, Int32, Int32)
using System;
class Sample {
public static void Main() {
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
string str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
int count;
int end;
start = str.Length-1;
end = start/2 - 1;
Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, end);
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The string 'he' occurs at position(s): ");
count = 0;
at = 0;
while((start > -1) && (at > -1))
{
count = start - end; //Count must be within the substring.
at = str.LastIndexOf("he", start, count);
if (at > -1)
{
Console.Write("{0} ", at);
start = at - 1;
}
}
Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
This example produces the following results:
All occurrences of 'he' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45
*/
// Sample for String.LastIndexOf(String, Int32, Int32)
open System
let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."
let mutable start = str.Length-1
let last = start / 2 - 1
printfn $"All occurrences of 'he' from position {start} to {last}."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The string 'he' occurs at position(s): "
let mutable at = 0
while (start > -1) && (at > -1) do
let count = start - last //Count must be within the substring.
at <- str.LastIndexOf("he", start, count)
if at > -1 then
printf $"{at} "
start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 'he' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45
*)
' Sample for String.LastIndexOf(String, Int32, Int32)
_
Class Sample
Public Shared Sub Main()
Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
Dim str As String = "Now is the time for all good men to come to the aid of their party."
Dim start As Integer
Dim at As Integer
Dim count As Integer
Dim [end] As Integer
start = str.Length - 1
[end] = start / 2 - 1
Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, [end])
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
Console.Write("The string 'he' occurs at position(s): ")
count = 0
at = 0
While start > - 1 And at > - 1
count = start - [end] 'Count must be within the substring.
at = str.LastIndexOf("he", start, count)
If at > - 1 Then
Console.Write("{0} ", at)
start = at - 1
End If
End While
Console.Write("{0}{0}{0}", Environment.NewLine)
End Sub
End Class
'
'This example produces the following results:
'All occurrences of 'he' from position 66 to 32.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The string 'he' occurs at position(s): 56 45
'
'
Комментарии
Нумерация индексов начинается с нуля. То есть первый символ в строке равен нулю индекса, а последний — Length 1.
Поиск начинается с startIndex позиции символа данного экземпляра и продолжается назад к началу, пока не value будет найдено или count не будет проверено положение символов. Например, если startIndex значение равно Length - 1, метод выполняет поиск обратных count символов из последнего символа в строке.
Этот метод выполняет поиск слова (с учетом регистра и языка и региональных параметров) с помощью текущего языка и региональных параметров.
Наборы символов включают игнорируемые символы, которые не учитываются при выполнении лингвистического или языка и региональных параметров. В поиске с учетом языка и региональных параметров, если value он содержит игнорируемый символ, результат эквивалентен поиску с помощью этого символа.
В следующем примере LastIndexOf метод используется для поиска позиции мягкого дефиса (U+00AD), за которым следует "m" или "n" в двух строках. Только одна из строк содержит мягкий дефис. В случае строки, которая включает мягкий дефис, за которым следует "m", LastIndexOf возвращает индекс "m" при поиске мягкого дефиса, за которым следует "m".
int position = 0;
string s1 = "ani\u00ADmal";
string s2 = "animal";
// Find the index of the soft hyphen followed by "n".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s1.LastIndexOf("\u00ADn", position, position + 1));
position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s2.LastIndexOf("\u00ADn", position, position + 1));
// Find the index of the soft hyphen followed by "m".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s1.LastIndexOf("\u00ADm", position, position + 1));
position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s2.LastIndexOf("\u00ADm", position, position + 1));
// The example displays the following output:
//
// 'm' at position 4
// 1
// 'm' at position 3
// 1
// 'm' at position 4
// 4
// 'm' at position 3
// 3
let s1 = "ani\u00ADmal"
let s2 = "animal"
// Find the index of the soft hyphen followed by "n".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s1.LastIndexOf("\u00ADn", position, position + 1)}"""
let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s2.LastIndexOf("\u00ADn", position, position + 1)}"""
// Find the index of the soft hyphen followed by "m".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s1.LastIndexOf("\u00ADm", position, position + 1)}"""
let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s2.LastIndexOf("\u00ADm", position, position + 1)}"""
// The example displays the following output:
//
// 'm' at position 4
// 1
// 'm' at position 3
// 1
// 'm' at position 4
// 4
// 'm' at position 3
// 3
Dim position As Integer
Dim softHyphen As String = ChrW(&HAD)
Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"
' Find the index of the soft hyphen followed by "n".
position = s1.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s1.LastIndexOf(softHyphen + "n", position, position + 1))
End If
position = s2.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s2.LastIndexOf(softHyphen + "n", position, position + 1))
End If
' Find the index of the soft hyphen followed by "m".
position = s1.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s1.LastIndexOf(softHyphen + "m", position, position + 1))
End If
position = s2.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s2.LastIndexOf(softHyphen + "m", position, position + 1))
End If
' The example displays the following output:
'
' 'm' at position 4
' 1
' 'm' at position 3
' 1
' 'm' at position 4
' 4
' 'm' at position 3
' 3
Примечания для тех, кто вызывает этот метод
Как описано в рекомендациях по использованию строк, рекомендуется избегать вызова методов сравнения строк, заменяющих значения по умолчанию и вызывающих методы, требующие явного указания параметров. Чтобы выполнить эту операцию с помощью правил сравнения текущего языка и региональных параметров, явно сообщите о намерении путем вызова LastIndexOf(String, Int32, Int32, StringComparison) перегрузки метода со значением CurrentCulture для параметра comparisonType . Если вам не требуется лингвистическое сравнение, рассмотрите возможность использования Ordinal.
См. также раздел
Применяется к
LastIndexOf(Char, Int32, StringComparison)
public:
int LastIndexOf(char value, int startIndex, StringComparison comparisonType);
public int LastIndexOf(char value, int startIndex, StringComparison comparisonType);
member this.LastIndexOf : char * int * StringComparison -> int
Public Function LastIndexOf (value As Char, startIndex As Integer, comparisonType As StringComparison) As Integer
Параметры
- value
- Char
- startIndex
- Int32
- comparisonType
- StringComparison
Возвращаемое значение
Применяется к
LastIndexOf(Char, Int32, Int32)
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
Сообщает отсчитывает отсчитываемое от нуля положение индекса последнего вхождения указанного символа Юникода в подстроке в этом экземпляре. Поиск начинается с указанной позиции символа и переходит к началу строки для указанного числа позиций символов.
public:
int LastIndexOf(char value, int startIndex, int count);
public int LastIndexOf(char value, int startIndex, int count);
member this.LastIndexOf : char * int * int -> int
Public Function LastIndexOf (value As Char, startIndex As Integer, count As Integer) As Integer
Параметры
- value
- Char
Символ Юникода для поиска.
- startIndex
- Int32
Начальная позиция поиска. Поиск начинается с startIndex начала этого экземпляра.
- count
- Int32
Число проверяемых позиций символов.
Возвращаемое значение
Отсчитываемое от нуля положение value индекса, если этот символ найден или -1, если он не найден или равен текущему экземпляру Empty.
Исключения
Текущий экземпляр не равен EmptystartIndex нулю или больше или равен длине этого экземпляра.
-или-
Текущий экземпляр не равен Empty, а startIndex - count +1 меньше нуля.
Примеры
Следующий пример находит индекс всех вхождения символов в подстроке, работая с конца подстроки до начала подстроки.
// Sample for String.LastIndexOf(Char, Int32, Int32)
using System;
class Sample {
public static void Main() {
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
string str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
int count;
int end;
start = str.Length-1;
end = start/2 - 1;
Console.WriteLine("All occurrences of 't' from position {0} to {1}.", start, end);
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The letter 't' occurs at position(s): ");
count = 0;
at = 0;
while((start > -1) && (at > -1))
{
count = start - end; //Count must be within the substring.
at = str.LastIndexOf('t', start, count);
if (at > -1)
{
Console.Write("{0} ", at);
start = at - 1;
}
}
Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33
*/
// Sample for String.LastIndexOf(Char, Int32, Int32)
open System
let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."
let mutable start = str.Length-1
let last = start / 2 - 1
printfn $"All occurrences of 't' from position {start} to {last}."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The letter 't' occurs at position(s): "
let mutable at = 0
while (start > -1) && (at > -1) do
let count = start - last //Count must be within the substring.
at <- str.LastIndexOf('t', start, count)
if at > -1 then
printf $"{at} "
start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 't' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33
*)
' Sample for String.LastIndexOf(Char, Int32, Int32)
_
Class Sample
Public Shared Sub Main()
Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
Dim str As String = "Now is the time for all good men to come to the aid of their party."
Dim start As Integer
Dim at As Integer
Dim count As Integer
Dim [end] As Integer
start = str.Length - 1
[end] = start / 2 - 1
Console.WriteLine("All occurrences of 't' from position {0} to {1}.", start, [end])
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
Console.Write("The letter 't' occurs at position(s): ")
count = 0
at = 0
While start > - 1 And at > - 1
count = start - [end] 'Count must be within the substring.
at = str.LastIndexOf("t"c, start, count)
If at > - 1 Then
Console.Write("{0} ", at)
start = at - 1
End If
End While
Console.Write("{0}{0}{0}", Environment.NewLine)
End Sub
End Class
'
'This example produces the following results:
'All occurrences of 't' from position 66 to 32.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The letter 't' occurs at position(s): 64 55 44 41 33
'
'
Комментарии
Нумерация индексов начинается с нуля. То есть первый символ в строке равен нулю индекса, а последний — Length 1.
Этот метод начинает поиск по startIndex позиции символа и продолжается назад к началу этого экземпляра, пока не value будет найдено или count не будет проверено положение символов. Например, если startIndex значение равно Length - 1, метод выполняет поиск обратных count символов из последнего символа в строке. Поиск учитывает регистр.
Этот метод выполняет порядковый поиск (без учета языка и региональных параметров), где символ считается эквивалентным другому символу, только если их скалярное значение Юникода совпадает. Чтобы выполнить поиск с учетом языка и региональных параметров, используйте CompareInfo.LastIndexOf метод, где скалярное значение Юникода, представляющее предварительно скомпилированные символы, например ligature "Æ" (U+00C6), может считаться эквивалентным любому вхождлению компонентов символа в правильной последовательности, например "AE" (U+0041, U+0045) в зависимости от языка и региональных параметров.
См. также раздел
Применяется к
LastIndexOf(String, Int32)
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
Сообщает о позиции индекса от нуля последнего вхождения указанной строки в этом экземпляре. Поиск начинается с указанной позиции символа и продолжается назад к началу строки.
public:
int LastIndexOf(System::String ^ value, int startIndex);
public int LastIndexOf(string value, int startIndex);
member this.LastIndexOf : string * int -> int
Public Function LastIndexOf (value As String, startIndex As Integer) As Integer
Параметры
- value
- String
Строка для поиска.
- startIndex
- Int32
Начальная позиция поиска. Поиск начинается с startIndex начала этого экземпляра.
Возвращаемое значение
Отсчитываемое от нуля положение value начального индекса, если эта строка найдена, или -1, если она не найдена или если текущий экземпляр равен Empty.
Исключения
value равно null.
Текущий экземпляр не равен EmptystartIndex нулю или больше длины текущего экземпляра.
-или-
Текущий экземпляр равен EmptystartIndex и меньше -1 или больше нуля.
Примеры
Следующий пример находит индекс всех вхождения строки в целевой строке, работая с конца целевой строки до начала целевой строки.
// Sample for String.LastIndexOf(String, Int32)
using System;
class Sample {
public static void Main() {
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
string str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
start = str.Length-1;
Console.WriteLine("All occurrences of 'he' from position {0} to 0.", start);
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The string 'he' occurs at position(s): ");
at = 0;
while((start > -1) && (at > -1))
{
at = str.LastIndexOf("he", start);
if (at > -1)
{
Console.Write("{0} ", at);
start = at - 1;
}
}
Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
This example produces the following results:
All occurrences of 'he' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45 8
*/
// Sample for String.LastIndexOf(String, Int32)
open System
let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."
let mutable start = str.Length - 1
printfn $"All occurrences of 'he' from position {start} to 0."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The string 'he' occurs at position(s): "
let mutable at = 0
while (start > -1) && (at > -1) do
at <- str.LastIndexOf("he", start)
if at > -1 then
printf $"{at} "
start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 'he' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45 8
*)
' Sample for String.LastIndexOf(String, Int32)
_
Class Sample
Public Shared Sub Main()
Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
Dim str As String = "Now is the time for all good men to come to the aid of their party."
Dim start As Integer
Dim at As Integer
'#3
start = str.Length - 1
Console.WriteLine("All occurrences of 'he' from position {0} to 0.", start)
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
Console.Write("The string 'he' occurs at position(s): ")
at = 0
While start > - 1 And at > - 1
at = str.LastIndexOf("he", start)
If at > - 1 Then
Console.Write("{0} ", at)
start = at - 1
End If
End While
Console.Write("{0}{0}{0}", Environment.NewLine)
End Sub
End Class
'
'This example produces the following results:
'All occurrences of 'he' from position 66 to 0.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The string 'he' occurs at position(s): 56 45 8
'
'
Комментарии
Нумерация индексов начинается с нуля. То есть первый символ в строке равен нулю индекса, а последний — Length 1.
Поиск начинается с startIndex позиции символа этого экземпляра и продолжается назад к началу, пока не value будет найдена или первая позиция символа была проверена. Например, если startIndex значение равно Length - 1, метод выполняет поиск каждого символа от последнего символа в строке до начала.
Этот метод выполняет поиск слова (с учетом регистра и языка и региональных параметров) с помощью текущего языка и региональных параметров.
Наборы символов включают игнорируемые символы, которые не учитываются при выполнении лингвистического или языка и региональных параметров. В поиске с учетом языка и региональных параметров, если value он содержит игнорируемый символ, результат эквивалентен поиску с помощью этого символа. В следующем примере LastIndexOf(String, Int32) метод используется для поиска подстроки, включающей мягкий дефис (U+00AD), и который предшествует или включает окончательное "m" в строку. Если пример выполняется в .NET Framework 4 или более поздней версии, так как мягкий дефис в строке поиска игнорируется, вызывая метод для поиска подстроки, состоящей из мягкого дефиса и "m", возвращает позицию "m" в строке, в то время как вызывает ее для поиска подстроки, состоящей из мягкого дефиса и "n", возвращает положение "n".
int position = 0;
string s1 = "ani\u00ADmal";
string s2 = "animal";
// Find the index of the soft hyphen followed by "n".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s1.LastIndexOf("\u00ADn", position));
position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s2.LastIndexOf("\u00ADn", position));
// Find the index of the soft hyphen followed by "m".
position = s1.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s1.LastIndexOf("\u00ADm", position));
position = s2.LastIndexOf("m");
Console.WriteLine($"'m' at position {position}");
if (position >= 0)
Console.WriteLine(s2.LastIndexOf("\u00ADm", position));
// The example displays the following output:
//
// 'm' at position 4
// 1
// 'm' at position 3
// 1
// 'm' at position 4
// 4
// 'm' at position 3
// 3
let s1 = "ani\u00ADmal"
let s2 = "animal"
// Find the index of the soft hyphen followed by "n".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s1.LastIndexOf("\u00ADn", position)}"""
let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s2.LastIndexOf("\u00ADn", position)}"""
// Find the index of the soft hyphen followed by "m".
let position = s1.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s1.LastIndexOf("\u00ADm", position)}"""
let position = s2.LastIndexOf "m"
printfn $"'m' at position {position}"
if position >= 0 then
printfn $"""{s2.LastIndexOf("\u00ADm", position)}"""
// The example displays the following output:
//
// 'm' at position 4
// 1
// 'm' at position 3
// 1
// 'm' at position 4
// 4
// 'm' at position 3
// 3
Dim position As Integer
Dim softHyphen As String = ChrW(&HAD)
Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"
' Find the index of the soft hyphen followed by "n".
position = s1.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s1.LastIndexOf(softHyphen + "n", position))
End If
position = s2.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s2.LastIndexOf(softHyphen + "n", position))
End If
' Find the index of the soft hyphen followed by "m".
position = s1.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s1.LastIndexOf(softHyphen + "m", position))
End If
position = s2.LastIndexOf("m")
Console.WriteLine($"'m' at position {position}")
If position >= 0 Then
Console.WriteLine(s2.LastIndexOf(softHyphen + "m", position))
End If
' The example displays the following output:
'
' 'm' at position 4
' 1
' 'm' at position 3
' 1
' 'm' at position 4
' 4
' 'm' at position 3
' 3
Примечания для тех, кто вызывает этот метод
Как описано в рекомендациях по использованию строк, рекомендуется избегать вызова методов сравнения строк, заменяющих значения по умолчанию и вызывающих методы, требующие явного указания параметров. Чтобы найти индекс подстроки, которая предшествует определенной позиции символов с помощью правил сравнения текущего языка и региональных параметров, сообщите о намерении явно путем вызова LastIndexOf(String, Int32, StringComparison) перегрузки метода со значением CurrentCulture для его comparisonType параметра. Если вам не требуется лингвистическое сравнение, рассмотрите возможность использования Ordinal.
См. также раздел
Применяется к
LastIndexOf(Rune, Int32)
public:
int LastIndexOf(System::Text::Rune value, int startIndex);
public int LastIndexOf(System.Text.Rune value, int startIndex);
member this.LastIndexOf : System.Text.Rune * int -> int
Public Function LastIndexOf (value As Rune, startIndex As Integer) As Integer
Параметры
- value
- Rune
- startIndex
- Int32
Возвращаемое значение
Применяется к
LastIndexOf(String, StringComparison)
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
Сообщает отсчитываемый от нуля индекс последнего вхождения указанной строки в текущем String объекте. Параметр указывает тип поиска, используемый для указанной строки.
public:
int LastIndexOf(System::String ^ value, StringComparison comparisonType);
public int LastIndexOf(string value, StringComparison comparisonType);
member this.LastIndexOf : string * StringComparison -> int
Public Function LastIndexOf (value As String, comparisonType As StringComparison) As Integer
Параметры
- value
- String
Строка для поиска.
- comparisonType
- StringComparison
Одно из значений перечисления, указывающее правила поиска.
Возвращаемое значение
Отсчитываемое от нуля положение начального value индекса параметра, если эта строка найдена, или -1, если она отсутствует.
Исключения
value равно null.
comparisonType недопустимое StringComparison значение.
Примеры
В следующем примере показаны три перегрузки LastIndexOf метода, которые находят последнее вхождение строки в другой строке с использованием различных значений перечисления StringComparison .
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
using System;
using System.Threading;
using System.Globalization;
class Sample
{
public static void Main()
{
string intro = "Find the last occurrence of a character using different " +
"values of StringComparison.";
string resultFmt = "Comparison: {0,-28} Location: {1,3}";
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
string CapitalAWithRing = "\u00c5";
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
string cat = "A Cheshire c" + "\u0061\u030a" + "t";
int loc = 0;
StringComparison[] scValues = {
StringComparison.CurrentCulture,
StringComparison.CurrentCultureIgnoreCase,
StringComparison.InvariantCulture,
StringComparison.InvariantCultureIgnoreCase,
StringComparison.Ordinal,
StringComparison.OrdinalIgnoreCase };
// Clear the screen and display an introduction.
Console.Clear();
Console.WriteLine(intro);
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Console.WriteLine("The current culture is \"{0}\" - {1}.",
Thread.CurrentThread.CurrentCulture.Name,
Thread.CurrentThread.CurrentCulture.DisplayName);
// Display the string to search for and the string to search.
Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"",
CapitalAWithRing, cat);
Console.WriteLine();
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
Console.WriteLine("Part 1: Start index and count are specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion. Specify the
// start index.
Console.WriteLine("\nPart 2: Start index is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc);
Console.WriteLine(resultFmt, sc, loc);
}
// Search using different values of StringComparsion.
Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
foreach (StringComparison sc in scValues)
{
loc = cat.LastIndexOf(CapitalAWithRing, sc);
Console.WriteLine(resultFmt, sc, loc);
}
}
}
/*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*/
// This code example demonstrates the
// System.String.LastIndexOf(String, ..., StringComparison) methods.
open System
open System.Threading
open System.Globalization
let intro = "Find the last occurrence of a character using different values of StringComparison."
// Define a string to search for.
// U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
let CapitalAWithRing = "\u00c5"
// Define a string to search.
// The result of combining the characters LATIN SMALL LETTER A and COMBINING
// RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
// LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
let cat = "A Cheshire c" + "\u0061\u030a" + "t"
let loc = 0
let scValues =
[| StringComparison.CurrentCulture
StringComparison.CurrentCultureIgnoreCase
StringComparison.InvariantCulture
StringComparison.InvariantCultureIgnoreCase
StringComparison.Ordinal
StringComparison.OrdinalIgnoreCase |]
// Clear the screen and display an introduction.
Console.Clear()
printfn $"{intro}"
// Display the current culture because culture affects the result. For example,
// try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture <- CultureInfo "en-US"
printfn $"The current culture is \"{Thread.CurrentThread.CurrentCulture.Name}\" - {Thread.CurrentThread.CurrentCulture.DisplayName}."
// Display the string to search for and the string to search.
printfn $"Search for the string \"{CapitalAWithRing}\" in the string \"{cat}\"\n"
// Note that in each of the following searches, we look for
// LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
// LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
// the string was not found.
// Search using different values of StringComparsion. Specify the start
// index and count.
printfn "Part 1: Start index and count are specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, cat.Length, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion. Specify the
// start index.
printfn "\nPart 2: Start index is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, cat.Length-1, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
// Search using different values of StringComparsion.
printfn "\nPart 3: Neither start index nor count is specified."
for sc in scValues do
let loc = cat.LastIndexOf(CapitalAWithRing, sc)
printfn $"Comparison: {sc,-28} Location: {loc,3}"
(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).
This code example produces the following results:
Find the last occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"
Part 1: Start index and count are specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 2: Start index is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture Location: -1
Comparison: CurrentCultureIgnoreCase Location: 12
Comparison: InvariantCulture Location: -1
Comparison: InvariantCultureIgnoreCase Location: 12
Comparison: Ordinal Location: -1
Comparison: OrdinalIgnoreCase Location: -1
*)
' This code example demonstrates the
' System.String.LastIndexOf(String, ..., StringComparison) methods.
Imports System.Threading
Imports System.Globalization
Class Sample
Public Shared Sub Main()
Dim intro As String = "Find the last occurrence of a character using different " & _
"values of StringComparison."
Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
' Define a string to search for.
' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
Dim CapitalAWithRing As String = "Å"
' Define a string to search.
' The result of combining the characters LATIN SMALL LETTER A and COMBINING
' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character
' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
Dim cat As String = "A Cheshire c" & "å" & "t"
Dim loc As Integer = 0
Dim scValues As StringComparison() = { _
StringComparison.CurrentCulture, _
StringComparison.CurrentCultureIgnoreCase, _
StringComparison.InvariantCulture, _
StringComparison.InvariantCultureIgnoreCase, _
StringComparison.Ordinal, _
StringComparison.OrdinalIgnoreCase }
Dim sc As StringComparison
' Clear the screen and display an introduction.
Console.Clear()
Console.WriteLine(intro)
' Display the current culture because culture affects the result. For example,
' try this code example with the "sv-SE" (Swedish-Sweden) culture.
Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
Console.WriteLine("The current culture is ""{0}"" - {1}.", _
Thread.CurrentThread.CurrentCulture.Name, _
Thread.CurrentThread.CurrentCulture.DisplayName)
' Display the string to search for and the string to search.
Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
CapitalAWithRing, cat)
Console.WriteLine()
' Note that in each of the following searches, we look for
' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains
' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates
' the string was not found.
' Search using different values of StringComparsion. Specify the start
' index and count.
Console.WriteLine("Part 1: Start index and count are specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, cat.Length, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion. Specify the
' start index.
Console.WriteLine(vbCrLf & "Part 2: Start index is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, cat.Length - 1, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
' Search using different values of StringComparsion.
Console.WriteLine(vbCrLf & "Part 3: Neither start index nor count is specified.")
For Each sc In scValues
loc = cat.LastIndexOf(CapitalAWithRing, sc)
Console.WriteLine(resultFmt, sc, loc)
Next sc
End Sub
End Class
'
'Note: This code example was executed on a console whose user interface
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the last occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture Location: -1
'Comparison: CurrentCultureIgnoreCase Location: 12
'Comparison: InvariantCulture Location: -1
'Comparison: InvariantCultureIgnoreCase Location: 12
'Comparison: Ordinal Location: -1
'Comparison: OrdinalIgnoreCase Location: -1
'
Комментарии
Нумерация индексов начинается с нуля. То есть первый символ в строке равен нулю индекса, а последний — Length 1.
Параметр comparisonType указывает для поиска value параметра с помощью:
- Текущий или инвариантный язык и региональные параметры.
- Поиск без учета регистра или регистра.
- Правила сравнения слов или порядкового номера.
Поиск начинается с последней позиции символа этого экземпляра и продолжается назад к началу до тех пор, пока не value будет обнаружена первая позиция символа.
Примечания для тех, кто вызывает этот метод
Наборы символов включают игнорируемые символы, которые не учитываются при выполнении лингвистического или языка и региональных параметров. В поиске с учетом языка и региональных параметров (т optionsOrdinalOrdinalIgnoreCase. е. в противном случае), если value он содержит игнорируемый символ, результат эквивалентен поиску с удаленным символом.
В следующем примере LastIndexOf(String, StringComparison) метод используется для поиска двух подстроок (обратимого дефиса, за которым следует "n" и обратимого дефиса, а затем "m") в двух строках. Только одна из строк содержит мягкий дефис. Если пример выполняется в .NET Framework 4 или более поздней версии, так как обратимый дефис является игнорируемым символом, поиск с учетом языка и региональных параметров возвращает то же значение, что он возвращает, если обратимый дефис не был включен в строку поиска. Однако порядковый поиск успешно находит мягкий дефис в одной строке и сообщает, что он отсутствует во второй строке.
string s1 = "ani\u00ADmal";
string s2 = "animal";
Console.WriteLine("Culture-sensitive comparison:");
// Use culture-sensitive comparison to find the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf("\u00ADn", StringComparison.CurrentCulture));
Console.WriteLine(s2.LastIndexOf("\u00ADn", StringComparison.CurrentCulture));
// Use culture-sensitive comparison to find the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf("\u00ADm", StringComparison.CurrentCulture));
Console.WriteLine(s2.LastIndexOf("\u00ADm", StringComparison.CurrentCulture));
Console.WriteLine("Ordinal comparison:");
// Use ordinal comparison to find the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf("\u00ADn", StringComparison.Ordinal));
Console.WriteLine(s2.LastIndexOf("\u00ADn", StringComparison.Ordinal));
// Use ordinal comparison to find the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf("\u00ADm", StringComparison.Ordinal));
Console.WriteLine(s2.LastIndexOf("\u00ADm", StringComparison.Ordinal));
// The example displays the following output:
//
// Culture-sensitive comparison:
// 1
// 1
// 4
// 3
// Ordinal comparison:
// -1
// -1
// 3
// -1
open System
let s1 = "ani\u00ADmal"
let s2 = "animal"
printfn "Culture-sensitive comparison:"
// Use culture-sensitive comparison to find the last soft hyphen followed by "n".
printfn $"""{s1.LastIndexOf("\u00ADn", StringComparison.CurrentCulture)}"""
printfn $"""{s2.LastIndexOf("\u00ADn", StringComparison.CurrentCulture)}"""
// Use culture-sensitive comparison to find the last soft hyphen followed by "m".
printfn $"""{s1.LastIndexOf("\u00ADm", StringComparison.CurrentCulture)}"""
printfn $"""{s2.LastIndexOf("\u00ADm", StringComparison.CurrentCulture)}"""
printfn "Ordinal comparison:"
// Use ordinal comparison to find the last soft hyphen followed by "n".
printfn $"""{s1.LastIndexOf("\u00ADn", StringComparison.Ordinal)}"""
printfn $"""{s2.LastIndexOf("\u00ADn", StringComparison.Ordinal)}"""
// Use ordinal comparison to find the last soft hyphen followed by "m".
printfn $"""{s1.LastIndexOf("\u00ADm", StringComparison.Ordinal)}"""
printfn $"""{s2.LastIndexOf("\u00ADm", StringComparison.Ordinal)}"""
// The example displays the following output:
//
// Culture-sensitive comparison:
// 1
// 1
// 4
// 3
// Ordinal comparison:
// -1
// -1
// 3
// -1
Dim softHyphen As String = ChrW(&HAD)
Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"
Console.WriteLine("Culture-sensitive comparison:")
' Use culture-sensitive comparison to find the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf(softHyphen + "n", StringComparison.CurrentCulture))
Console.WriteLine(s2.LastIndexOf(softHyphen + "n", StringComparison.CurrentCulture))
' Use culture-sensitive comparison to find the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf(softHyphen + "m", StringComparison.CurrentCulture))
Console.WriteLine(s2.LastIndexOf(softHyphen + "m", StringComparison.CurrentCulture))
Console.WriteLine("Ordinal comparison:")
' Use ordinal comparison to find the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf(softHyphen + "n", StringComparison.Ordinal))
Console.WriteLine(s2.LastIndexOf(softHyphen + "n", StringComparison.Ordinal))
' Use ordinal comparison to find the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf(softHyphen + "m", StringComparison.Ordinal))
Console.WriteLine(s2.LastIndexOf(softHyphen + "m", StringComparison.Ordinal))
' The example displays the following output:
'
' Culture-sensitive comparison:
' 1
' 1
' 4
' 3
' Ordinal comparison:
' -1
' -1
' 3
' -1
Применяется к
LastIndexOf(Rune, Int32, Int32, StringComparison)
public:
int LastIndexOf(System::Text::Rune value, int startIndex, int count, StringComparison comparisonType);
public int LastIndexOf(System.Text.Rune value, int startIndex, int count, StringComparison comparisonType);
member this.LastIndexOf : System.Text.Rune * int * int * StringComparison -> int
Public Function LastIndexOf (value As Rune, startIndex As Integer, count As Integer, comparisonType As StringComparison) As Integer
Параметры
- value
- Rune
- startIndex
- Int32
- count
- Int32
- comparisonType
- StringComparison
Возвращаемое значение
Применяется к
LastIndexOf(Char, StringComparison)
public:
int LastIndexOf(char value, StringComparison comparisonType);
public int LastIndexOf(char value, StringComparison comparisonType);
member this.LastIndexOf : char * StringComparison -> int
Public Function LastIndexOf (value As Char, comparisonType As StringComparison) As Integer
Параметры
- value
- Char
- comparisonType
- StringComparison
Возвращаемое значение
Применяется к
LastIndexOf(Char, Int32)
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
Сообщает о позиции индекса от нуля последнего вхождения указанного символа Юникода в этом экземпляре. Поиск начинается с указанной позиции символа и продолжается назад к началу строки.
public:
int LastIndexOf(char value, int startIndex);
public int LastIndexOf(char value, int startIndex);
member this.LastIndexOf : char * int -> int
Public Function LastIndexOf (value As Char, startIndex As Integer) As Integer
Параметры
- value
- Char
Символ Юникода для поиска.
- startIndex
- Int32
Начальная позиция поиска. Поиск начинается с startIndex начала этого экземпляра.
Возвращаемое значение
Отсчитываемое от нуля положение value индекса, если этот символ найден или -1, если он не найден или равен текущему экземпляру Empty.
Исключения
Текущий экземпляр не равен EmptystartIndex нулю или больше или равен длине этого экземпляра.
Примеры
Следующий пример находит индекс всех вхождения символов в строке, работающих с конца строки до начала строки.
// Sample for String.LastIndexOf(Char, Int32)
using System;
class Sample {
public static void Main() {
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
string str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
start = str.Length-1;
Console.WriteLine("All occurrences of 't' from position {0} to 0.", start);
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The letter 't' occurs at position(s): ");
at = 0;
while((start > -1) && (at > -1))
{
at = str.LastIndexOf('t', start);
if (at > -1)
{
Console.Write("{0} ", at);
start = at - 1;
}
}
Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33 11 7
*/
// Sample for String.LastIndexOf(Char, Int32)
open System
let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."
let mutable start = str.Length - 1
printfn $"All occurrences of 't' from position {start} to 0."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The letter 't' occurs at position(s): "
let mutable at = 0
while (start > -1) && (at > -1) do
at <- str.LastIndexOf('t', start)
if at > -1 then
printf $"{at} "
start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 't' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33 11 7
*)
' Sample for String.LastIndexOf(Char, Int32)
Imports System
_
Class Sample
Public Shared Sub Main()
Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
Dim str As String = "Now is the time for all good men to come to the aid of their party."
Dim start As Integer
Dim at As Integer
start = str.Length - 1
Console.WriteLine("All occurrences of 't' from position {0} to 0.", start)
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
Console.Write("The letter 't' occurs at position(s): ")
at = 0
While start > - 1 And at > - 1
at = str.LastIndexOf("t"c, start)
If at > - 1 Then
Console.Write("{0} ", at)
start = at - 1
End If
End While
Console.Write("{0}{0}{0}", Environment.NewLine)
End Sub
End Class
'
'This example produces the following results:
'All occurrences of 't' from position 66 to 0.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The letter 't' occurs at position(s): 64 55 44 41 33 11 7
'
Комментарии
Нумерация индексов начинается с нуля. То есть первый символ в строке равен нулю индекса, а последний — Length 1. Этот метод начинает поиск по startIndex позиции символа этого экземпляра и переходит к началу текущего экземпляра до тех пор, пока не value будет найдена или первая позиция символа была проверена. Например, если startIndex значение равно Length - 1, метод выполняет поиск каждого символа от последнего символа в строке до начала. Поиск учитывает регистр.
Этот метод выполняет порядковый поиск (без учета языка и региональных параметров), где символ считается эквивалентным другому символу, только если их скалярные значения Юникода совпадают. Чтобы выполнить поиск с учетом языка и региональных параметров, используйте CompareInfo.LastIndexOf метод, где скалярное значение Юникода, представляющее предварительно скомпилированные символы, например ligature "Æ" (U+00C6), может считаться эквивалентным любому вхождлению компонентов символа в правильной последовательности, например "AE" (U+0041, U+0045) в зависимости от языка и региональных параметров.
См. также раздел
Применяется к
LastIndexOf(String)
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
Сообщает о позиции индекса от нуля последнего вхождения указанной строки в этом экземпляре.
public:
int LastIndexOf(System::String ^ value);
public int LastIndexOf(string value);
member this.LastIndexOf : string -> int
Public Function LastIndexOf (value As String) As Integer
Параметры
- value
- String
Строка для поиска.
Возвращаемое значение
Отсчитываемое от нуля положение value начального индекса, если эта строка найдена, или -1, если она отсутствует.
Исключения
value равно null.
Примеры
В следующем примере удаляются открывающие и закрывающие HTML-теги из строки, если теги начинаются и заканчиваются строкой. Если строка заканчивается символом закрывающей скобки (">"), в примере используется LastIndexOf метод для поиска начала конечного тега.
using System;
public class Example
{
public static void Main()
{
string[] strSource = { "<b>This is bold text</b>", "<H1>This is large Text</H1>",
"<b><i><font color=green>This has multiple tags</font></i></b>",
"<b>This has <i>embedded</i> tags.</b>",
"This line ends with a greater than symbol and should not be modified>" };
// Strip HTML start and end tags from each string if they are present.
foreach (string s in strSource)
{
Console.WriteLine("Before: " + s);
string item = s;
// Use EndsWith to find a tag at the end of the line.
if (item.Trim().EndsWith(">"))
{
// Locate the opening tag.
int endTagStartPosition = item.LastIndexOf("</");
// Remove the identified section, if it is valid.
if (endTagStartPosition >= 0 )
item = item.Substring(0, endTagStartPosition);
// Use StartsWith to find the opening tag.
if (item.Trim().StartsWith("<"))
{
// Locate the end of opening tab.
int openTagEndPosition = item.IndexOf(">");
// Remove the identified section, if it is valid.
if (openTagEndPosition >= 0)
item = item.Substring(openTagEndPosition + 1);
}
}
// Display the trimmed string.
Console.WriteLine("After: " + item);
Console.WriteLine();
}
}
}
// The example displays the following output:
// Before: <b>This is bold text</b>
// After: This is bold text
//
// Before: <H1>This is large Text</H1>
// After: This is large Text
//
// Before: <b><i><font color=green>This has multiple tags</font></i></b>
// After: <i><font color=green>This has multiple tags</font></i>
//
// Before: <b>This has <i>embedded</i> tags.</b>
// After: This has <i>embedded</i> tags.
//
// Before: This line ends with a greater than symbol and should not be modified>
// After: This line ends with a greater than symbol and should not be modified>
let strSource =
[| "<b>This is bold text</b>"; "<H1>This is large Text</H1>"
"<b><i><font color=green>This has multiple tags</font></i></b>"
"<b>This has <i>embedded</i> tags.</b>"
"This line ends with a greater than symbol and should not be modified>" |]
// Strip HTML start and end tags from each string if they are present.
for s in strSource do
printfn $"Before: {s}"
let mutable item = s
// Use EndsWith to find a tag at the end of the line.
if item.Trim().EndsWith ">" then
// Locate the opening tag.
let endTagStartPosition = item.LastIndexOf "</"
// Remove the identified section, if it is valid.
if endTagStartPosition >= 0 then
item <- item.Substring(0, endTagStartPosition)
// Use StartsWith to find the opening tag.
if item.Trim().StartsWith "<" then
// Locate the end of opening tab.
let openTagEndPosition = item.IndexOf ">"
// Remove the identified section, if it is valid.
if openTagEndPosition >= 0 then
item <- item.Substring(openTagEndPosition + 1)
// Display the trimmed string.
printfn "After: {item}"
printfn ""
// The example displays the following output:
// Before: <b>This is bold text</b>
// After: This is bold text
//
// Before: <H1>This is large Text</H1>
// After: This is large Text
//
// Before: <b><i><font color=green>This has multiple tags</font></i></b>
// After: <i><font color=green>This has multiple tags</font></i>
//
// Before: <b>This has <i>embedded</i> tags.</b>
// After: This has <i>embedded</i> tags.
//
// Before: This line ends with a greater than symbol and should not be modified>
// After: This line ends with a greater than symbol and should not be modified>
Module Example
Public Sub Main()
Dim strSource As String() = { "<b>This is bold text</b>", _
"<H1>This is large Text</H1>", _
"<b><i><font color=green>This has multiple tags</font></i></b>", _
"<b>This has <i>embedded</i> tags.</b>", _
"This line ends with a greater than symbol and should not be modified>" }
' Strip HTML start and end tags from each string if they are present.
For Each s As String In strSource
Console.WriteLine("Before: " + s)
' Use EndsWith to find a tag at the end of the line.
If s.Trim().EndsWith(">") Then
' Locate the opening tag.
Dim endTagStartPosition As Integer = s.LastIndexOf("</")
' Remove the identified section if it is valid.
If endTagStartPosition >= 0 Then
s = s.Substring(0, endTagStartPosition)
End If
' Use StartsWith to find the opening tag.
If s.Trim().StartsWith("<") Then
' Locate the end of opening tab.
Dim openTagEndPosition As Integer = s.IndexOf(">")
' Remove the identified section if it is valid.
If openTagEndPosition >= 0 Then
s = s.Substring(openTagEndPosition + 1)
End If
End If
End If
' Display the trimmed string.
Console.WriteLine("After: " + s)
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' Before: <b>This is bold text</b>
' After: This is bold text
'
' Before: <H1>This is large Text</H1>
' After: This is large Text
'
' Before: <b><i><font color=green>This has multiple tags</font></i></b>
' After: <i><font color=green>This has multiple tags</font></i>
'
' Before: <b>This has <i>embedded</i> tags.</b>
' After: This has <i>embedded</i> tags.
'
' Before: This line ends with a greater than symbol and should not be modified>
' After: This line ends with a greater than symbol and should not be modified>
Комментарии
Нумерация индексов начинается с нуля. То есть первый символ в строке равен нулю индекса, а последний — Length 1.
Поиск начинается с последней позиции символа этого экземпляра и продолжается назад к началу до тех пор, пока не value будет обнаружена первая позиция символа.
Этот метод выполняет поиск слова (с учетом регистра и языка и региональных параметров) с помощью текущего языка и региональных параметров.
Наборы символов включают игнорируемые символы, которые не учитываются при выполнении лингвистического или языка и региональных параметров. В поиске с учетом языка и региональных параметров, если value он содержит игнорируемый символ, результат эквивалентен поиску с помощью этого символа.
В следующем примере LastIndexOf(String) метод используется для поиска двух подстроок (обратимого дефиса, за которым следует "n" и обратимого дефиса, за которым следует "m") в двух строках. Только одна из строк содержит мягкий дефис. Если пример выполняется в .NET Framework 4 или более поздней версии, в каждом случае, так как мягкий дефис является игнорируемым символом, результат будет таким же, как если бы мягкий дефис не был включен.value
string s1 = "ani\u00ADmal";
string s2 = "animal";
// Find the index of the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf("\u00ADn"));
Console.WriteLine(s2.LastIndexOf("\u00ADn"));
// Find the index of the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf("\u00ADm"));
Console.WriteLine(s2.LastIndexOf("\u00ADm"));
// The example displays the following output:
//
// 1
// 1
// 4
// 3
let s1 = "ani\u00ADmal"
let s2 = "animal"
// Find the index of the last soft hyphen followed by "n".
printfn $"""{s1.LastIndexOf "\u00ADn"}"""
printfn $"""{s2.LastIndexOf "\u00ADn"}"""
// Find the index of the last soft hyphen followed by "m".
printfn $"""{s1.LastIndexOf "\u00ADm"}"""
printfn $"""{s2.LastIndexOf "\u00ADm"}"""
// The example displays the following output:
//
// 1
// 1
// 4
// 3
Dim softHyphen As String = ChrW(&HAD)
Dim s1 As String = "ani" + softHyphen + "mal"
Dim s2 As String = "animal"
' Find the index of the last soft hyphen followed by "n".
Console.WriteLine(s1.LastIndexOf(softHyphen + "n"))
Console.WriteLine(s2.LastIndexOf(softHyphen + "n"))
' Find the index of the last soft hyphen followed by "m".
Console.WriteLine(s1.LastIndexOf(softHyphen + "m"))
Console.WriteLine(s2.LastIndexOf(softHyphen + "m"))
' The example displays the following output:
'
' 1
' 1
' 4
' 3
Примечания для тех, кто вызывает этот метод
Как описано в рекомендациях по использованию строк, рекомендуется избегать вызова методов сравнения строк, заменяющих значения по умолчанию и вызывающих методы, требующие явного указания параметров. Чтобы найти последний индекс подстроки в строковом экземпляре с помощью правил сравнения текущего языка и региональных параметров, явно сообщите о намерении путем вызова LastIndexOf(String, StringComparison) перегрузки метода со значением CurrentCulture для его comparisonType параметра. Если вам не требуется лингвистическое сравнение, рассмотрите возможность использования Ordinal.
См. также раздел
Применяется к
LastIndexOf(Char)
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
- Исходный код:
- String.Searching.cs
Сообщает о позиции индекса от нуля последнего вхождения указанного символа Юникода в этом экземпляре.
public:
int LastIndexOf(char value);
public int LastIndexOf(char value);
member this.LastIndexOf : char -> int
Public Function LastIndexOf (value As Char) As Integer
Параметры
- value
- Char
Символ Юникода для поиска.
Возвращаемое значение
Отсчитываемое от нуля положение value индекса, если этот символ найден или -1, если он отсутствует.
Примеры
В следующем примере определяется ExtractFilename метод, который использует LastIndexOf(Char) метод для поиска последнего символа разделителя каталогов в строке и извлечения имени файла строки. Если файл существует, метод возвращает имя файла без его пути.
using System;
using System.IO;
public class TestLastIndexOf
{
public static void Main()
{
string filename;
filename = ExtractFilename(@"C:\temp\");
Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
filename = ExtractFilename(@"C:\temp\delegate.txt");
Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
filename = ExtractFilename("delegate.txt");
Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
filename = ExtractFilename(@"C:\temp\notafile.txt");
Console.WriteLine("{0}", String.IsNullOrEmpty(filename) ? "<none>" : filename);
}
public static string ExtractFilename(string filepath)
{
// If path ends with a "\", it's a path only so return String.Empty.
if (filepath.Trim().EndsWith(@"\"))
return String.Empty;
// Determine where last backslash is.
int position = filepath.LastIndexOf('\\');
// If there is no backslash, assume that this is a filename.
if (position == -1)
{
// Determine whether file exists in the current directory.
if (File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath))
return filepath;
else
return String.Empty;
}
else
{
// Determine whether file exists using filepath.
if (File.Exists(filepath))
// Return filename without file path.
return filepath.Substring(position + 1);
else
return String.Empty;
}
}
}
open System
open System.IO
let extractFilename (filepath: string) =
// If path ends with a "\", it's a path only so return String.Empty.
if filepath.Trim().EndsWith @"\" then
String.Empty
else
// Determine where last backslash is.
let position = filepath.LastIndexOf '\\'
// If there is no backslash, assume that this is a filename.
if position = -1 then
// Determine whether file exists in the current directory.
if File.Exists(Environment.CurrentDirectory + string Path.DirectorySeparatorChar + filepath) then
filepath
else
String.Empty
else
// Determine whether file exists using filepath.
if File.Exists filepath then
// Return filename without file path.
filepath.Substring(position + 1)
else
String.Empty
do
let filename = extractFilename @"C:\temp\"
printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""
let filename = extractFilename @"C:\temp\delegate.txt"
printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""
let filename = extractFilename "delegate.txt"
printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""
let filename = extractFilename @"C:\temp\notafile.txt"
printfn $"""{if String.IsNullOrEmpty filename then "<none>" else filename}"""
Imports System.IO
Public Module Test
Public Sub Main()
Dim filename As String
filename = ExtractFilename("C:\temp\")
Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
filename = ExtractFilename("C:\temp\delegate.txt")
Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
filename = ExtractFilename("delegate.txt")
Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
filename = ExtractFilename("C:\temp\notafile.txt")
Console.WriteLine("{0}", IIf(String.IsNullOrEmpty(fileName), "<none>", filename))
End Sub
Public Function ExtractFilename(filepath As String) As String
' If path ends with a "\", it's a path only so return String.Empty.
If filepath.Trim().EndsWith("\") Then Return String.Empty
' Determine where last backslash is.
Dim position As Integer = filepath.LastIndexOf("\"c)
' If there is no backslash, assume that this is a filename.
If position = -1 Then
' Determine whether file exists in the current directory.
If File.Exists(Environment.CurrentDirectory + Path.DirectorySeparatorChar + filepath) Then
Return filepath
Else
Return String.Empty
End If
Else
' Determine whether file exists using filepath.
If File.Exists(filepath) Then
' Return filename without file path.
Return filepath.Substring(position + 1)
Else
Return String.Empty
End If
End If
End Function
End Module
' The example displays the following output:
' delegate.txt
Комментарии
Нумерация индексов начинается с нуля. То есть первый символ в строке равен нулю индекса, а последний — Length 1.
Этот метод начинает поиск в последней позиции символа этого экземпляра и переходит к началу до тех пор, пока не value будет найдена или первая позиция символа была проверена. Поиск учитывает регистр.
Этот метод выполняет порядковый поиск (без учета языка и региональных параметров), где символ считается эквивалентным другому символу, только если их скалярные значения Юникода совпадают. Чтобы выполнить поиск с учетом языка и региональных параметров, используйте CompareInfo.LastIndexOf метод, где скалярное значение Юникода, представляющее предварительно скомпилированные символы, например ligature "Æ" (U+00C6), может считаться эквивалентным любому вхождлению компонентов символа в правильной последовательности, например "AE" (U+0041, U+0045) в зависимости от языка и региональных параметров.
См. также раздел
Применяется к
LastIndexOf(Rune, StringComparison)
public:
int LastIndexOf(System::Text::Rune value, StringComparison comparisonType);
public int LastIndexOf(System.Text.Rune value, StringComparison comparisonType);
member this.LastIndexOf : System.Text.Rune * StringComparison -> int
Public Function LastIndexOf (value As Rune, comparisonType As StringComparison) As Integer
Параметры
- value
- Rune
- comparisonType
- StringComparison