String.LastIndexOf 메서드
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
이 인스턴스에서 마지막으로 발견되는 지정된 유니코드 문자 또는 문자열의 0부터 시작하는 인덱스 위치를 보고합니다. 이 인스턴스에 해당 문자나 문자열이 없으면 이 메서드는 -1을 반환합니다.
오버로드
LastIndexOf(String, Int32, Int32, StringComparison) |
이 인스턴스에서 마지막으로 발견되는 지정된 문자열의 0부터 시작하는 인덱스 위치를 보고합니다. 지정된 문자 위치에서 검색을 시작하여 지정된 수의 문자 위치에 대한 문자열의 시작 부분 쪽으로 뒤로 검색합니다. 매개 변수는 지정된 문자열을 검색할 때 수행할 비교 유형을 지정합니다. |
LastIndexOf(String, Int32, Int32) |
이 인스턴스에서 마지막으로 발견되는 지정된 문자열의 0부터 시작하는 인덱스 위치를 보고합니다. 지정된 문자 위치에서 검색을 시작하여 지정된 수의 문자 위치에 대한 문자열의 시작 부분 쪽으로 뒤로 검색합니다. |
LastIndexOf(Char, Int32, Int32) |
이 인스턴스의 부분 문자열에서 마지막으로 발견되는 지정된 유니코드 문자의 0부터 시작하는 인덱스 위치를 보고합니다. 지정된 문자 위치에서 검색을 시작하여 지정된 수의 문자 위치에 대한 문자열의 시작 부분 쪽으로 뒤로 검색합니다. |
LastIndexOf(String, StringComparison) |
현재 String 개체에서 마지막으로 발견되는 지정된 문자열의 0부터 시작하는 인덱스를 보고합니다. 매개 변수는 지정된 문자열에 사용할 검색 유형을 지정합니다. |
LastIndexOf(String, Int32, StringComparison) |
현재 String 개체에서 마지막으로 발견되는 지정된 문자열의 0부터 시작하는 인덱스를 보고합니다. 지정된 문자 위치에서 시작하고 문자열의 시작 부분을 향해 뒤로 검색이 진행됩니다. 매개 변수는 지정된 문자열을 검색할 때 수행할 비교 유형을 지정합니다. |
LastIndexOf(Char, Int32) |
이 인스턴스에서 마지막으로 발견되는 지정된 유니코드 문자의 0부터 시작하는 인덱스 위치를 보고합니다. 지정된 문자 위치에서 시작하고 문자열의 시작 부분을 향해 뒤로 검색이 진행됩니다. |
LastIndexOf(String) |
이 인스턴스에서 마지막으로 발견되는 지정된 문자열의 0부터 시작하는 인덱스 위치를 보고합니다. |
LastIndexOf(Char) |
이 인스턴스에서 마지막으로 발견되는 지정된 유니코드 문자의 0부터 시작하는 인덱스 위치를 보고합니다. |
LastIndexOf(String, Int32) |
이 인스턴스에서 마지막으로 발견되는 지정된 문자열의 0부터 시작하는 인덱스 위치를 보고합니다. 지정된 문자 위치에서 시작하고 문자열의 시작 부분을 향해 뒤로 검색이 진행됩니다. |
LastIndexOf(String, Int32, Int32, StringComparison)
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
이 인스턴스에서 마지막으로 발견되는 지정된 문자열의 0부터 시작하는 인덱스 위치를 보고합니다. 지정된 문자 위치에서 검색을 시작하여 지정된 수의 문자 위치에 대한 문자열의 시작 부분 쪽으로 뒤로 검색합니다. 매개 변수는 지정된 문자열을 검색할 때 수행할 비교 유형을 지정합니다.
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
매개 변수의 인덱스 위치(0부터 시작)이고, 해당 문자열이 없거나 현재 인스턴스가 Empty와 같으면 -1입니다.
예외
value
은 null
입니다.
count
가 음수입니다.
또는
현재 인스턴스가 Empty와 같지 않고 startIndex
가 음수입니다.
또는
현재 인스턴스가 Empty와 같지 않고 startIndex
가 이 인스턴스의 길이보다 큽니다.
또는
현재 인스턴스가 Empty와 같지 않고 startIndex
- count
+ 1이 이 인스턴스 외부의 위치를 지정합니다.
또는
현재 인스턴스가 Empty이고 start
가 -1보다 작거나 0보다 큽니다.
또는
현재 인스턴스가 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
'
설명
인덱스 번호 매기기 시작은 0부터 시작합니다. 즉, 문자열의 첫 번째 문자는 인덱스 0이고 마지막 문자는 - 1입니다 Length .
검색은 문자 위치에서 시작하여 startIndex
찾거나 count
문자 위치를 검사할 때까지 value
뒤로 진행됩니다. 예를 들어 가 Length - 1이면 startIndex
메서드는 문자열의 마지막 문자에서 역방향 count
문자를 검색합니다.
매개 변수는 comparisonType
다음을 사용하여 매개 변수를 value
검색하도록 지정합니다.
- 현재 또는 고정 문화권입니다.
- 대/소문자를 구분하거나 대/소문자를 구분하지 않는 검색입니다.
- Word 또는 서수 비교 규칙입니다.
호출자 참고
문자 집합에는 무시할 수 있는 문자가 포함되며, 이들 문자는 언어 또는 문화권 구분 비교를 수행하는 경우 고려되지 않습니다. 문화권 구분 검색(즉, comparisonType
이 Ordinal 또는 OrdinalIgnoreCase가 아닌 경우)에서는 value
에 무시할 수 있는 문자가 포함된 경우 결과는 해당 문자가 제거된 대상을 검색하는 것과 같습니다.
다음 예제 LastIndexOf(String, Int32, Int32, StringComparison) 에서 메서드는 두 문자열의 마지막 "m" 앞에 첫 번째 문자 위치를 제외한 모든 에서 소프트 하이픈(U+00AD) 뒤에 "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(String, Int32, Int32)
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
이 인스턴스에서 마지막으로 발견되는 지정된 문자열의 0부터 시작하는 인덱스 위치를 보고합니다. 지정된 문자 위치에서 검색을 시작하여 지정된 수의 문자 위치에 대한 문자열의 시작 부분 쪽으로 뒤로 검색합니다.
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
의 인덱스 위치(0부터 시작)이고, 해당 문자열이 없거나 현재 인스턴스가 Empty와 같으면 -1입니다.
예외
value
은 null
입니다.
count
가 음수입니다.
또는
현재 인스턴스가 Empty와 같지 않고 startIndex
가 음수입니다.
또는
현재 인스턴스가 Empty와 같지 않고 startIndex
가 이 인스턴스의 길이보다 큽니다.
또는
현재 인스턴스가 Empty와 같지 않고 startIndex
- count
+ 1이 이 인스턴스 외부의 위치를 지정합니다.
또는
현재 인스턴스가 Empty이고 start
가 -1보다 작거나 0보다 큽니다.
또는
현재 인스턴스가 Empty이고 count
가 1보다 큽니다.
예제
다음 예제에서는 부분 문자열의 끝에서 부분 문자열의 시작 부분 문자열의 시작까지 작동 하는 문자열의 모든 발생 인덱스를 찾습니다.
// Sample for String::LastIndexOf(String, Int32, Int32)
using namespace System;
int main()
{
String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
String^ str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
int count;
int end;
start = str->Length - 1;
end = start / 2 - 1;
Console::WriteLine( "All occurrences of 'he' from position {0} to {1}.", start, end );
Console::WriteLine( "{1}{0}{2}{0}{3}{0}", Environment::NewLine, br1, br2, str );
Console::Write( "The string 'he' occurs at position(s): " );
count = 0;
at = 0;
while ( (start > -1) && (at > -1) )
{
count = start - end; //Count must be within the substring.
at = str->LastIndexOf( "he", start, count );
if ( at > -1 )
{
Console::Write( "{0} ", at );
start = at - 1;
}
}
Console::Write( "{0} {0} {0}", Environment::NewLine );
}
/*
This example produces the following results:
All occurrences of 'he' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45
*/
// Sample for String.LastIndexOf(String, Int32, Int32)
using System;
class Sample {
public static void Main() {
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
string str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
int count;
int end;
start = str.Length-1;
end = start/2 - 1;
Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, end);
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The string 'he' occurs at position(s): ");
count = 0;
at = 0;
while((start > -1) && (at > -1))
{
count = start - end; //Count must be within the substring.
at = str.LastIndexOf("he", start, count);
if (at > -1)
{
Console.Write("{0} ", at);
start = at - 1;
}
}
Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
This example produces the following results:
All occurrences of 'he' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45
*/
// Sample for String.LastIndexOf(String, Int32, Int32)
open System
let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."
let mutable start = str.Length-1
let last = start / 2 - 1
printfn $"All occurrences of 'he' from position {start} to {last}."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The string 'he' occurs at position(s): "
let mutable at = 0
while (start > -1) && (at > -1) do
let count = start - last //Count must be within the substring.
at <- str.LastIndexOf("he", start, count)
if at > -1 then
printf $"{at} "
start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 'he' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45
*)
' Sample for String.LastIndexOf(String, Int32, Int32)
_
Class Sample
Public Shared Sub Main()
Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
Dim str As String = "Now is the time for all good men to come to the aid of their party."
Dim start As Integer
Dim at As Integer
Dim count As Integer
Dim [end] As Integer
start = str.Length - 1
[end] = start / 2 - 1
Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, [end])
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
Console.Write("The string 'he' occurs at position(s): ")
count = 0
at = 0
While start > - 1 And at > - 1
count = start - [end] 'Count must be within the substring.
at = str.LastIndexOf("he", start, count)
If at > - 1 Then
Console.Write("{0} ", at)
start = at - 1
End If
End While
Console.Write("{0}{0}{0}", Environment.NewLine)
End Sub
End Class
'
'This example produces the following results:
'All occurrences of 'he' from position 66 to 32.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The string 'he' occurs at position(s): 56 45
'
'
설명
인덱스 번호 매기기 는 0부터 시작합니다. 즉, 문자열의 첫 번째 문자는 인덱스 0이고 마지막 문자는 - 1입니다 Length .
검색은 이 instance 문자 위치에서 시작하여 startIndex
검색 위치가 발견되거나 count
문자 위치를 검사할 때까지 value
시작 부분으로 뒤로 진행됩니다. 예를 들어 가 Length - 1이면 startIndex
메서드는 문자열의 마지막 문자에서 뒤로 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
호출자 참고
문자열 사용에 대한 모범 사례에 설명된 대로 기본값을 대체하는 문자열 비교 메서드를 호출하지 말고 매개 변수를 명시적으로 지정해야 하는 메서드를 호출하는 것이 좋습니다. 현재 문화권의 비교 규칙을 사용하여 이 작업을 수행하려면 해당 매개 변수에 대한 값 CurrentCulture 으로 메서드 오버로드를 호출 LastIndexOf(String, Int32, Int32, StringComparison) 하여 명시적으로 의도를 comparisonType
알릴 수 있습니다. 언어 인식 비교가 필요하지 않은 경우 를 사용하는 Ordinal것이 좋습니다.
추가 정보
적용 대상
LastIndexOf(Char, Int32, Int32)
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
이 인스턴스의 부분 문자열에서 마지막으로 발견되는 지정된 유니코드 문자의 0부터 시작하는 인덱스 위치를 보고합니다. 지정된 문자 위치에서 검색을 시작하여 지정된 수의 문자 위치에 대한 문자열의 시작 부분 쪽으로 뒤로 검색합니다.
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
의 인덱스 위치(0부터 시작)이고, 해당 문자가 없거나 현재 인스턴스가 Empty와 같으면 -1입니다.
예외
현재 인스턴스가 Empty와 같지 않고 startIndex
가 0보다 작거나 이 인스턴스의 길이보다 크거나 같습니다.
또는
현재 인스턴스가 Empty와 같지 않고 startIndex
- count
+ 1이 0보다 작습니다.
예제
다음 예제에서는 부분 문자열의 끝에서 부분 문자열의 시작까지 작동하는 부분 문자열에 있는 모든 문자의 인덱스를 찾습니다.
// Sample for String::LastIndexOf(Char, Int32, Int32)
using namespace System;
int main()
{
String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
String^ str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
int count;
int end;
start = str->Length - 1;
end = start / 2 - 1;
Console::WriteLine( "All occurrences of 't' from position {0} to {1}.", start, end );
Console::WriteLine( "\n{0}\n{1}\n{2}", br1, br2, str );
Console::Write( "The letter 't' occurs at position(s): " );
count = 0;
at = 0;
while ( (start > -1) && (at > -1) )
{
count = start - end; //Count must be within the substring.
at = str->LastIndexOf( 't', start, count );
if ( at > -1 )
{
Console::Write( " {0} ", at );
start = at - 1;
}
}
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33
*/
// Sample for String.LastIndexOf(Char, Int32, Int32)
using System;
class Sample {
public static void Main() {
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
string str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
int count;
int end;
start = str.Length-1;
end = start/2 - 1;
Console.WriteLine("All occurrences of 't' from position {0} to {1}.", start, end);
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The letter 't' occurs at position(s): ");
count = 0;
at = 0;
while((start > -1) && (at > -1))
{
count = start - end; //Count must be within the substring.
at = str.LastIndexOf('t', start, count);
if (at > -1)
{
Console.Write("{0} ", at);
start = at - 1;
}
}
Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33
*/
// Sample for String.LastIndexOf(Char, Int32, Int32)
open System
let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."
let mutable start = str.Length-1
let last = start / 2 - 1
printfn $"All occurrences of 't' from position {start} to {last}."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The letter 't' occurs at position(s): "
let mutable at = 0
while (start > -1) && (at > -1) do
let count = start - last //Count must be within the substring.
at <- str.LastIndexOf('t', start, count)
if at > -1 then
printf $"{at} "
start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 't' from position 66 to 32.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33
*)
' Sample for String.LastIndexOf(Char, Int32, Int32)
_
Class Sample
Public Shared Sub Main()
Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
Dim str As String = "Now is the time for all good men to come to the aid of their party."
Dim start As Integer
Dim at As Integer
Dim count As Integer
Dim [end] As Integer
start = str.Length - 1
[end] = start / 2 - 1
Console.WriteLine("All occurrences of 't' from position {0} to {1}.", start, [end])
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
Console.Write("The letter 't' occurs at position(s): ")
count = 0
at = 0
While start > - 1 And at > - 1
count = start - [end] 'Count must be within the substring.
at = str.LastIndexOf("t"c, start, count)
If at > - 1 Then
Console.Write("{0} ", at)
start = at - 1
End If
End While
Console.Write("{0}{0}{0}", Environment.NewLine)
End Sub
End Class
'
'This example produces the following results:
'All occurrences of 't' from position 66 to 32.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The letter 't' occurs at position(s): 64 55 44 41 33
'
'
설명
인덱스 번호 매기기 는 0부터 시작합니다. 즉, 문자열의 첫 번째 문자는 인덱스 0이고 마지막 문자는 - 1입니다 Length .
이 메서드는 문자 위치에서 검색을 startIndex
시작하고 가 발견되거나 count
문자 위치를 검사할 때까지 value
이 instance 시작 부분으로 뒤로 진행됩니다. 예를 들어 가 Length - 1이면 startIndex
메서드는 문자열의 마지막 문자에서 뒤로 count
문자를 검색합니다. 검색은 대/소문자를 구분합니다.
이 메서드는 서수(문화권을 구분하지 않는) 검색을 수행합니다. 여기서 문자는 유니코드 스칼라 값이 동일한 경우에만 다른 문자와 동일한 것으로 간주됩니다. 문화권에 민감한 검색을 수행하려면 메서드를 사용합니다 CompareInfo.LastIndexOf . 여기서 합자 "Æ"(U+00C6)와 같이 미리 구성된 문자를 나타내는 유니코드 스칼라 값은 문화권에 따라 "AE"(U+0041, U+0045)와 같은 올바른 시퀀스에서 문자의 구성 요소가 발생하는 것과 동일한 것으로 간주될 수 있습니다.
추가 정보
적용 대상
LastIndexOf(String, StringComparison)
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
현재 String 개체에서 마지막으로 발견되는 지정된 문자열의 0부터 시작하는 인덱스를 보고합니다. 매개 변수는 지정된 문자열에 사용할 검색 유형을 지정합니다.
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
매개 변수의 0부터 시작하는 인덱스 위치이고, 그렇지 않으면 -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
'
설명
인덱스 번호 매기기 는 0부터 시작합니다. 즉, 문자열의 첫 번째 문자는 인덱스 0이고 마지막 문자는 - 1입니다 Length .
매개 변수는 comparisonType
다음을 사용하여 매개 변수를 value
검색하도록 지정합니다.
- 현재 또는 고정 문화권입니다.
- 대/소문자를 구분하거나 대/소문자를 구분하지 않는 검색입니다.
- Word 또는 서수 비교 규칙입니다.
이 instance 마지막 문자 위치에서 검색이 시작되고 가 발견되거나 첫 번째 문자 위치가 검사될 때까지 value
시작 부분으로 뒤로 진행됩니다.
호출자 참고
문자 집합에는 무시할 수 있는 문자가 포함되며, 이들 문자는 언어 또는 문화권 구분 비교를 수행하는 경우 고려되지 않습니다. 문화권 구분 검색(즉, options
이 Ordinal 또는 OrdinalIgnoreCase가 아닌 경우)에서는 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(String, Int32, StringComparison)
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
현재 String 개체에서 마지막으로 발견되는 지정된 문자열의 0부터 시작하는 인덱스를 보고합니다. 지정된 문자 위치에서 시작하고 문자열의 시작 부분을 향해 뒤로 검색이 진행됩니다. 매개 변수는 지정된 문자열을 검색할 때 수행할 비교 유형을 지정합니다.
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
매개 변수의 인덱스 위치(0부터 시작)이고, 해당 문자열이 없거나 현재 인스턴스가 Empty와 같으면 -1입니다.
예외
value
은 null
입니다.
현재 인스턴스가 Empty와 같지 않고 startIndex
가 0보다 작거나 현재 인스턴스의 길이보다 큽니다.
또는
현재 인스턴스가 Empty와 같고 startIndex
가 -1보다 작거나 0보다 큽니다.
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
'
설명
인덱스 번호 매기기 는 0부터 시작합니다. 즉, 문자열의 첫 번째 문자는 인덱스 0이고 마지막 문자는 - 1입니다 Length .
검색은 문자 위치에서 시작하여 startIndex
가 발견되거나 첫 번째 문자 위치가 검사될 때까지 value
뒤로 진행됩니다. 예를 들어 가 Length - 1이면 startIndex
메서드는 문자열의 마지막 문자에서 시작까지 모든 문자를 검색합니다.
매개 변수는 comparisonType
현재 또는 고정 문화권, 대/소문자 구분 또는 대/소문자를 구분하지 않는 검색, 단어 또는 서수 비교 규칙을 사용하여 매개 변수를 검색하도록 지정 value
합니다.
호출자 참고
문자 집합에는 무시할 수 있는 문자가 포함되며, 이들 문자는 언어 또는 문화권 구분 비교를 수행하는 경우 고려되지 않습니다. 문화권 구분 검색(즉, comparisonType
이 Ordinal 또는 OrdinalIgnoreCase가 아닌 경우)에서는 value
에 무시할 수 있는 문자가 포함된 경우 결과는 해당 문자가 제거된 대상을 검색하는 것과 같습니다.
다음 예제 LastIndexOf(String, Int32, StringComparison) 에서는 메서드를 사용하여 두 문자열의 마지막 "m"부터 소프트 하이픈(U+00AD) 뒤에 "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(Char, Int32)
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
이 인스턴스에서 마지막으로 발견되는 지정된 유니코드 문자의 0부터 시작하는 인덱스 위치를 보고합니다. 지정된 문자 위치에서 시작하고 문자열의 시작 부분을 향해 뒤로 검색이 진행됩니다.
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
의 인덱스 위치(0부터 시작)이고, 해당 문자가 없거나 현재 인스턴스가 Empty와 같으면 -1입니다.
예외
현재 인스턴스가 Empty와 같지 않고 startIndex
가 0보다 작거나 이 인스턴스의 길이보다 크거나 같습니다.
예제
다음 예제에서는 문자열의 끝에서 문자열의 시작까지 작업하는 문자열에 있는 모든 문자의 인덱스를 찾습니다.
// Sample for String::LastIndexOf(Char, Int32)
using namespace System;
int main()
{
String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
String^ str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
start = str->Length - 1;
Console::WriteLine( "All occurrences of 't' from position {0} to 0.", start );
Console::WriteLine( "{0}\n{1}\n{2}\n", br1, br2, str );
Console::Write( "The letter 't' occurs at position(s): " );
at = 0;
while ( (start > -1) && (at > -1) )
{
at = str->LastIndexOf( 't', start );
if ( at > -1 )
{
Console::Write( " {0} ", at );
start = at - 1;
}
}
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33 11 7
*/
// Sample for String.LastIndexOf(Char, Int32)
using System;
class Sample {
public static void Main() {
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
string str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
start = str.Length-1;
Console.WriteLine("All occurrences of 't' from position {0} to 0.", start);
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The letter 't' occurs at position(s): ");
at = 0;
while((start > -1) && (at > -1))
{
at = str.LastIndexOf('t', start);
if (at > -1)
{
Console.Write("{0} ", at);
start = at - 1;
}
}
Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33 11 7
*/
// Sample for String.LastIndexOf(Char, Int32)
open System
let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."
let mutable start = str.Length - 1
printfn $"All occurrences of 't' from position {start} to 0."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The letter 't' occurs at position(s): "
let mutable at = 0
while (start > -1) && (at > -1) do
at <- str.LastIndexOf('t', start)
if at > -1 then
printf $"{at} "
start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 't' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The letter 't' occurs at position(s): 64 55 44 41 33 11 7
*)
' Sample for String.LastIndexOf(Char, Int32)
Imports System
_
Class Sample
Public Shared Sub Main()
Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
Dim str As String = "Now is the time for all good men to come to the aid of their party."
Dim start As Integer
Dim at As Integer
start = str.Length - 1
Console.WriteLine("All occurrences of 't' from position {0} to 0.", start)
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
Console.Write("The letter 't' occurs at position(s): ")
at = 0
While start > - 1 And at > - 1
at = str.LastIndexOf("t"c, start)
If at > - 1 Then
Console.Write("{0} ", at)
start = at - 1
End If
End While
Console.Write("{0}{0}{0}", Environment.NewLine)
End Sub
End Class
'
'This example produces the following results:
'All occurrences of 't' from position 66 to 0.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The letter 't' occurs at position(s): 64 55 44 41 33 11 7
'
설명
인덱스 번호 매기기 는 0부터 시작합니다. 즉, 문자열의 첫 번째 문자는 인덱스 0이고 마지막 문자는 - 1입니다 Length . 이 메서드는 이 instance 문자 위치에서 검색 startIndex
을 시작하고 가 발견되거나 첫 번째 문자 위치를 검사할 때까지 value
현재 instance 시작 부분으로 뒤로 진행합니다. 예를 들어 가 Length - 1이면 startIndex
메서드는 문자열의 마지막 문자에서 시작까지 모든 문자를 검색합니다. 검색은 대/소문자를 구분합니다.
이 메서드는 서수(문화권을 구분하지 않는) 검색을 수행합니다. 여기서 문자는 유니코드 스칼라 값이 동일한 경우에만 다른 문자와 동일한 것으로 간주됩니다. 문화권에 민감한 검색을 수행하려면 메서드를 사용합니다 CompareInfo.LastIndexOf . 여기서 합자 "Æ"(U+00C6)와 같이 미리 구성된 문자를 나타내는 유니코드 스칼라 값은 문화권에 따라 "AE"(U+0041, U+0045)와 같은 올바른 시퀀스에서 문자의 구성 요소가 발생하는 것과 동일한 것으로 간주될 수 있습니다.
추가 정보
적용 대상
LastIndexOf(String)
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
이 인스턴스에서 마지막으로 발견되는 지정된 문자열의 0부터 시작하는 인덱스 위치를 보고합니다.
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
의 0부터 시작하는 인덱스 위치이고, 그러지 않으면 -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>
설명
인덱스 번호 매기기 시작은 0부터 시작합니다. 즉, 문자열의 첫 번째 문자는 인덱스 0이고 마지막 문자는 - 1입니다 Length .
검색은 이 instance 마지막 문자 위치에서 시작하여 첫 번째 문자 위치가 발견되거나 첫 번째 문자 위치를 검사할 때까지 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
호출자 참고
문자열 사용에 대한 모범 사례에 설명된 대로 기본값을 대체하는 문자열 비교 메서드를 호출하지 말고 매개 변수를 명시적으로 지정해야 하는 메서드를 호출하는 것이 좋습니다. 현재 문화권의 비교 규칙을 사용하여 문자열 instance 내에서 부분 문자열의 마지막 인덱스 를 찾으려면 해당 매개 변수에 대한 comparisonType
값 CurrentCulture 으로 메서드 오버로드를 호출 LastIndexOf(String, StringComparison) 하여 명시적으로 의도를 알릴 수 있습니다. 언어 인식 비교가 필요하지 않은 경우 를 사용하는 Ordinal것이 좋습니다.
추가 정보
적용 대상
LastIndexOf(Char)
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
이 인스턴스에서 마지막으로 발견되는 지정된 유니코드 문자의 0부터 시작하는 인덱스 위치를 보고합니다.
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
의 인덱스 위치(0부터 시작)이고, 그렇지 않으면 -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
설명
인덱스 번호 매기기 시작은 0부터 시작합니다. 즉, 문자열의 첫 번째 문자는 인덱스 0이고 마지막 문자는 - 1입니다 Length .
이 메서드는 이 instance 마지막 문자 위치에서 검색을 시작하고 가 발견되거나 첫 번째 문자 위치를 검사할 때까지 value
시작 부분으로 뒤로 진행합니다. 검색은 대/소문자를 구분합니다.
이 메서드는 서수(문화권을 구분하지 않는) 검색을 수행합니다. 여기서 문자는 유니코드 스칼라 값이 동일한 경우에만 다른 문자와 동등한 것으로 간주됩니다. 문화권에 민감한 검색을 수행하려면 메서드를 사용합니다 CompareInfo.LastIndexOf . 여기서 합자 "Æ"(U+00C6)와 같이 미리 컴파일된 문자를 나타내는 유니코드 스칼라 값은 문화권에 따라 "AE"(U+0041, U+0045)와 같은 올바른 순서로 문자 구성 요소가 발생하는 것과 동일한 것으로 간주될 수 있습니다.
추가 정보
적용 대상
LastIndexOf(String, Int32)
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
- Source:
- String.Searching.cs
이 인스턴스에서 마지막으로 발견되는 지정된 문자열의 0부터 시작하는 인덱스 위치를 보고합니다. 지정된 문자 위치에서 시작하고 문자열의 시작 부분을 향해 뒤로 검색이 진행됩니다.
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
의 인덱스 위치(0부터 시작)이고, 해당 문자열이 없거나 현재 인스턴스가 Empty와 같으면 -1입니다.
예외
value
은 null
입니다.
현재 인스턴스가 Empty와 같지 않고 startIndex
가 0보다 작거나 현재 인스턴스의 길이보다 큽니다.
또는
현재 인스턴스가 Empty와 같고 startIndex
가 -1보다 작거나 0보다 큽니다.
예제
다음 예제에서는 대상 문자열의 끝에서 대상 문자열의 시작까지 작업하는 대상 문자열에서 문자열이 발생하는 모든 항목의 인덱스를 찾습니다.
// Sample for String::LastIndexOf(String, Int32)
using namespace System;
int main()
{
String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
String^ str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
start = str->Length - 1;
Console::WriteLine( "All occurrences of 'he' from position {0} to 0.", start );
Console::WriteLine( "{0}\n{1}\n{2}\n", br1, br2, str );
Console::Write( "The string 'he' occurs at position(s): " );
at = 0;
while ( (start > -1) && (at > -1) )
{
at = str->LastIndexOf( "he", start );
if ( at > -1 )
{
Console::Write( " {0} ", at );
start = at - 1;
}
}
Console::WriteLine();
}
/*
This example produces the following results:
All occurrences of 'he' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45 8
*/
// Sample for String.LastIndexOf(String, Int32)
using System;
class Sample {
public static void Main() {
string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
string str = "Now is the time for all good men to come to the aid of their party.";
int start;
int at;
start = str.Length-1;
Console.WriteLine("All occurrences of 'he' from position {0} to 0.", start);
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
Console.Write("The string 'he' occurs at position(s): ");
at = 0;
while((start > -1) && (at > -1))
{
at = str.LastIndexOf("he", start);
if (at > -1)
{
Console.Write("{0} ", at);
start = at - 1;
}
}
Console.Write("{0}{0}{0}", Environment.NewLine);
}
}
/*
This example produces the following results:
All occurrences of 'he' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45 8
*/
// Sample for String.LastIndexOf(String, Int32)
open System
let br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
let br2 = "0123456789012345678901234567890123456789012345678901234567890123456"
let str = "Now is the time for all good men to come to the aid of their party."
let mutable start = str.Length - 1
printfn $"All occurrences of 'he' from position {start} to 0."
printfn $"{br1}{Environment.NewLine}{br2}{Environment.NewLine}{str}{Environment.NewLine}"
printf "The string 'he' occurs at position(s): "
let mutable at = 0
while (start > -1) && (at > -1) do
at <- str.LastIndexOf("he", start)
if at > -1 then
printf $"{at} "
start <- at - 1
printf $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}"
(*
This example produces the following results:
All occurrences of 'he' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.
The string 'he' occurs at position(s): 56 45 8
*)
' Sample for String.LastIndexOf(String, Int32)
_
Class Sample
Public Shared Sub Main()
Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
Dim str As String = "Now is the time for all good men to come to the aid of their party."
Dim start As Integer
Dim at As Integer
'#3
start = str.Length - 1
Console.WriteLine("All occurrences of 'he' from position {0} to 0.", start)
Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
Console.Write("The string 'he' occurs at position(s): ")
at = 0
While start > - 1 And at > - 1
at = str.LastIndexOf("he", start)
If at > - 1 Then
Console.Write("{0} ", at)
start = at - 1
End If
End While
Console.Write("{0}{0}{0}", Environment.NewLine)
End Sub
End Class
'
'This example produces the following results:
'All occurrences of 'he' from position 66 to 0.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The string 'he' occurs at position(s): 56 45 8
'
'
설명
인덱스 번호 매기기 시작은 0부터 시작합니다. 즉, 문자열의 첫 번째 문자는 인덱스 0이고 마지막 문자는 - 1입니다 Length .
검색은 이 instance 문자 위치에서 시작하여 startIndex
첫 번째 문자 위치가 발견되거나 첫 번째 문자 위치를 검사할 때까지 value
시작 부분으로 뒤로 진행됩니다. 예를 들어 가 Length - 1이면 startIndex
메서드는 문자열의 마지막 문자에서 시작까지 모든 문자를 검색합니다.
이 메서드는 현재 문화권을 사용하여 단어(대/소문자 구분 및 문화권 구분) 검색을 수행합니다.
문자 집합에는 무시할 수 있는 문자가 포함되며, 이들 문자는 언어 또는 문화권 구분 비교를 수행하는 경우 고려되지 않습니다. 문화권 구분 검색에서는 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
호출자 참고
문자열 사용에 대한 모범 사례에 설명된 대로 기본값을 대체하는 문자열 비교 메서드를 호출하지 말고 매개 변수를 명시적으로 지정해야 하는 메서드를 호출하는 것이 좋습니다. 현재 문화권의 비교 규칙을 사용하여 특정 문자 위치 앞에 오는 부분 문자열의 인덱스를 찾으려면 해당 매개 변수에 대한 comparisonType
값 CurrentCulture 으로 메서드 오버로드를 호출 LastIndexOf(String, Int32, StringComparison) 하여 명시적으로 의도를 알릴 수 있습니다. 언어 인식 비교가 필요하지 않은 경우 를 사용하는 Ordinal것이 좋습니다.
추가 정보
적용 대상
.NET
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기