String.IndexOf 方法

定义

报告指定 Unicode 字符或字符串在此实例中的第一个匹配项的从零开始的索引。 如果未在此实例中找到该字符或字符串,则此方法返回 -1。

重载

IndexOf(String, Int32, Int32)

报告指定字符串在此实例中的第一个匹配项的从零开始的索引。 搜索从指定字符位置开始,并检查指定数量的字符位置。

IndexOf(String, Int32, Int32, StringComparison)

报告指定的字符串在当前 String 对象中的第一个匹配项的从零开始的索引。 参数指定当前字符串中的起始搜索位置、要搜索的当前字符串中的字符数量,以及要用于指定字符串的搜索类型。

IndexOf(String, Int32, StringComparison)

报告指定的字符串在当前 String 对象中的第一个匹配项的从零开始的索引。 参数指定当前字符串中的起始搜索位置以及用于指定字符串的搜索类型。

IndexOf(String, StringComparison)

报告指定的字符串在当前 String 对象中的第一个匹配项的从零开始的索引。 一个参数指定要用于指定字符串的搜索类型。

IndexOf(Char, Int32, Int32)

报告指定字符在此实例中的第一个匹配项的从零开始的索引。 搜索从指定字符位置开始,并检查指定数量的字符位置。

IndexOf(Char, StringComparison)

报告指定 Unicode 字符在此字符串中的第一个匹配项的从零开始的索引。 一个参数指定要用于指定字符的搜索类型。

IndexOf(Char, Int32)

报告指定 Unicode 字符在此字符串中的第一个匹配项的从零开始的索引。 该搜索从指定字符位置开始。

IndexOf(String)

报告指定字符串在此实例中的第一个匹配项的从零开始的索引。

IndexOf(Char)

报告指定 Unicode 字符在此字符串中的第一个匹配项的从零开始的索引。

IndexOf(String, Int32)

报告指定字符串在此实例中的第一个匹配项的从零开始的索引。 该搜索从指定字符位置开始。

IndexOf(String, Int32, Int32)

报告指定字符串在此实例中的第一个匹配项的从零开始的索引。 搜索从指定字符位置开始,并检查指定数量的字符位置。

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

参数

value
String

要搜寻的字符串。

startIndex
Int32

搜索起始位置。

count
Int32

要检查的字符位置数。

返回

如果找到该字符串,则为从当前实例的起始位置开始的从零开始的 value 的索引位置;否则为 -1。 如果 valueEmpty,则返回值为 startIndex

例外

valuenull

countstartIndex 为负数。

startIndex 大于此字符串的长度。

count 大于此字符串的长度减 startIndex

示例

以下示例查找另一个字符串的子字符串中字符串“he”的所有匹配项的索引。 请注意,必须为每个搜索迭代重新计算要搜索的字符数。

// Sample for String::IndexOf(String, Int32, Int32)
using namespace System;
int main()
{
   String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
   String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
   String^ str = "Now is the time for all good men to come to the aid of their party.";
   int start;
   int at;
   int end;
   int count;
   end = str->Length;
   start = end / 2;
   Console::WriteLine();
   Console::WriteLine( "All occurrences of 'he' from position {0} to {1}.", start, end - 1 );
   Console::WriteLine( "{1}{0}{2}{0}{3}{0}", Environment::NewLine, br1, br2, str );
   Console::Write( "The string 'he' occurs at position(s): " );
   count = 0;
   at = 0;
   while ( (start <= end) && (at > -1) )
   {
      
      // start+count must be a position within -str-.
      count = end - start;
      at = str->IndexOf( "he", start, count );
      if ( at == -1 )
            break;

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

   Console::WriteLine();
}

/*
This example produces the following results:

All occurrences of 'he' from position 33 to 66.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

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

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

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

count = 0;
at = 0;
while((start <= end) && (at > -1))
{
    // start+count must be a position within -str-.
    count = end - start;
    at = str.IndexOf("he", start, count);
    if (at == -1) break;
    Console.Write("{0} ", at);
    start = at+1;
}
Console.WriteLine();

/*
This example produces the following results:

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

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

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

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

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

(*
This example produces the following results:

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

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

*)
' Sample for String.IndexOf(String, Int32, Int32)
Class Sample
   
   Public Shared Sub Main()
      
      Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
      Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
      Dim str As String = "Now is the time for all good men to come to the aid of their party."
      Dim start As Integer
      Dim at As Integer
      Dim [end] As Integer
      Dim count As Integer
      
      [end] = str.Length
      start = [end] / 2
      Console.WriteLine()
      Console.WriteLine("All occurrences of 'he' from position {0} to {1}.", start, [end] - 1)
      Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str)
      Console.Write("The string 'he' occurs at position(s): ")
      
      count = 0
      at = 0
      While start <= [end] AndAlso at > - 1
         ' start+count must be a position within -str-.
         count = [end] - start
         at = str.IndexOf("he", start, count)
         If at = - 1 Then
            Exit While
         End If
         Console.Write("{0} ", at)
         start = at + 1
      End While
      Console.WriteLine()
   End Sub
End Class
'
'This example produces the following results:
'
'All occurrences of 'he' from position 33 to 66.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The string 'he' occurs at position(s): 45 56
'
'

注解

索引编号从 0 开始 (零) 。 startIndex 参数可以介于 0 到字符串实例的长度。

此方法使用当前区域性执行单词 (区分大小写和区分区域性) 搜索。 搜索从 开始 startIndex ,并持续到 startIndex + count -1。 在 startIndex + count 的字符不包含在搜索中。

字符集包括可忽略字符,在执行语言性的或区分区域性的比较时该字符不被考虑。 在区分区域性的搜索中,如果 value 包含一个可忽略字符,则结果与移除了该字符的搜索等效。 如果 value 仅包含一个或多个可忽略字符,则 IndexOf(String, Int32, Int32) 方法始终返回 startIndex,这是搜索开始的字符位置。 在以下示例中 IndexOf(String, Int32, Int32) ,方法用于查找软连字符的位置, (U+00AD) 后跟一个“m”,该位置从两个字符串中的第三个字符位置到第六个字符位置开始。 只有一个字符串包含必需的子字符串。 如果在 .NET Framework 4 或更高版本上运行该示例,则在这两种情况下,由于软连字符是可忽略字符,则该方法在执行区分区域性的比较时,会返回字符串中“m”的索引。 注意对于第一个字符串,包含软连字符后跟“m”,该方法无法返回该软连字符的索引,而是返回“m”的索引。

using System;

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

        Console.WriteLine(s1.IndexOf(searchString, 2, 4));
        Console.WriteLine(s2.IndexOf(searchString, 2, 4));

        // The example displays the following output:
        //       4
        //       3
    }
}
let searchString = "\u00ADm"
let s1 = "ani\u00ADmal"
let s2 = "animal"

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

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

      Console.WriteLine(s1.IndexOf(searchString, 2, 4))
      Console.WriteLine(s2.IndexOf(searchString, 2, 4))
   End Sub
End Module
' The example displays the following output:
'       4
'       3

调用方说明

使用字符串的最佳做法中所述,建议避免调用替换默认值的字符串比较方法,而是调用需要显式指定参数的方法。 若要使用当前区域性的比较规则执行此操作,请通过为其参数调用 IndexOf(String, Int32, Int32, StringComparison) 值为 CurrentCulturecomparisonType 的方法重载来显式发出信号。 如果不需要语言感知比较,请考虑使用 Ordinal

另请参阅

适用于

IndexOf(String, Int32, Int32, StringComparison)

报告指定的字符串在当前 String 对象中的第一个匹配项的从零开始的索引。 参数指定当前字符串中的起始搜索位置、要搜索的当前字符串中的字符数量,以及要用于指定字符串的搜索类型。

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

参数

value
String

要搜寻的字符串。

startIndex
Int32

搜索起始位置。

count
Int32

要检查的字符位置数。

comparisonType
StringComparison

指定搜索规则的枚举值之一。

返回

如果找到该字符串,则为从当前实例的起始位置开始的从零开始的 value 参数索引位置;否则为 -1。 如果 valueEmpty,则返回值为 startIndex

例外

valuenull

countstartIndex 为负数。

startIndex 大于此实例的长度。

count 大于此字符串的长度减 startIndex

comparisonType 不是有效的 StringComparison 值。

示例

以下示例演示 方法的 IndexOf 三个重载,这些重载使用枚举的不同值在另一个字符串中查找字符串的第 StringComparison 一个匹配项。

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

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

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the first occurrence of a character using different " + 
                   "values of StringComparison.";
    string resultFmt = "Comparison: {0,-28} Location: {1,3}";

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

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

    int loc = 0;
    StringComparison[] scValues = {
        StringComparison.CurrentCulture,
        StringComparison.CurrentCultureIgnoreCase,
        StringComparison.InvariantCulture,
        StringComparison.InvariantCultureIgnoreCase,
        StringComparison.Ordinal,
        StringComparison.OrdinalIgnoreCase };

// Clear the screen and display an introduction.
    Console.Clear();
    Console.WriteLine(intro);

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

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    Console.WriteLine("The current culture is \"{0}\" - {1}.", 
                       Thread.CurrentThread.CurrentCulture.Name,
                       Thread.CurrentThread.CurrentCulture.DisplayName);

// Display the string to search for and the string to search.
    Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"", 
                       CapitalAWithRing, cat);
    Console.WriteLine();

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

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

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

// Search using different values of StringComparison. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(CapitalAWithRing, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }
    }
}

/*
Note: This code example was executed on a console whose user interface 
culture is "en-US" (English-United States).

This code example produces the following results:

Find the first occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

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

open System
open System.Threading
open System.Globalization

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

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

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

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

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

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

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

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

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

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

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

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

(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).

This code example produces the following results:

Find the first occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

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

Imports System.Threading
Imports System.Globalization

Class Sample
    Public Shared Sub Main() 
        Dim intro As String = "Find the first occurrence of a character using different " & _
                              "values of StringComparison."
        Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
        
        ' Define a string to search for.
        ' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
        Dim CapitalAWithRing As String = "Å"
        
        ' Define a string to search. 
        ' The result of combining the characters LATIN SMALL LETTER A and COMBINING 
        ' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character 
        ' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
        Dim cat As String = "A Cheshire c" & "å" & "t"
        
        Dim loc As Integer = 0
        Dim scValues As StringComparison() =  { _
                        StringComparison.CurrentCulture, _
                        StringComparison.CurrentCultureIgnoreCase, _
                        StringComparison.InvariantCulture, _
                        StringComparison.InvariantCultureIgnoreCase, _
                        StringComparison.Ordinal, _
                        StringComparison.OrdinalIgnoreCase }
        Dim sc As StringComparison
        
        ' Clear the screen and display an introduction.
        Console.Clear()
        Console.WriteLine(intro)
        
        ' Display the current culture because culture affects the result. For example, 
        ' try this code example with the "sv-SE" (Swedish-Sweden) culture.
        Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
        Console.WriteLine("The current culture is ""{0}"" - {1}.", _
                           Thread.CurrentThread.CurrentCulture.Name, _ 
                           Thread.CurrentThread.CurrentCulture.DisplayName)
        
        ' Display the string to search for and the string to search.
        Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
                           CapitalAWithRing, cat)
        Console.WriteLine()
        
        ' Note that in each of the following searches, we look for 
        ' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains 
        ' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates 
        ' the string was not found.
        ' Search using different values of StringComparison. Specify the start 
        ' index and count.

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

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

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

'
'Note: This code example was executed on a console whose user interface 
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the first occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'

注解

索引编号从 0 开始 (零) 。 startIndex 参数可以介于 0 到字符串实例的长度。

搜索从 开始 startIndex ,并持续到 startIndex + count -1。 在 startIndex + count 的字符不包含在搜索中。

参数 comparisonType 指定使用当前或固定区域性、使用区分大小写或不区分大小写的搜索,以及使用单词或序号比较规则来搜索 value 参数。

调用方说明

字符集包括可忽略字符,在执行语言性的或区分区域性的比较时该字符不被考虑。 在区分区域性的搜索 (即,如果 comparisonType 不是 OrdinalOrdinalIgnoreCase) 中,如果 value 包含一个可忽略字符,则结果与移除了该字符的搜索等效。 如果 value 仅包含一个或多个可忽略字符,则 IndexOf(String, Int32, Int32, StringComparison) 方法始终返回 startIndex,这是搜索开始的字符位置。

在以下示例中 IndexOf(String, Int32, Int32, StringComparison) ,方法用于查找软连字符的位置, (U+00AD) 后跟一个“m”,该位置从两个字符串中的第三个字符位置到第六个字符位置开始。 只有一个字符串包含必需的子字符串。 如果在 .NET Framework 4 或更高版本上运行该示例,则在这两种情况下,由于软连字符是可忽略字符,则该方法在执行区分区域性的比较时,会返回字符串中“m”的索引。 但是,当它执行序号比较时,它仅在第一个字符串中查找子字符串。 请注意,对于第一个字符串(包括后跟“m”的软连字符),方法无法返回软连字符的索引,而是在执行区分区域性的比较时返回“m”的索引。 只有当此方法执行序号比较时,它才会在第一个字符串中返回软连字符的索引。

using System;

public class Example
{
    public static void Main()
    {

        string searchString = "\u00ADm";
        string s1 = "ani\u00ADmal" ;
        string s2 = "animal";

        Console.WriteLine(s1.IndexOf(searchString, 2, 4, StringComparison.CurrentCulture));
        Console.WriteLine(s1.IndexOf(searchString, 2, 4, StringComparison.Ordinal));
        Console.WriteLine(s2.IndexOf(searchString, 2, 4, StringComparison.CurrentCulture));
        Console.WriteLine(s2.IndexOf(searchString, 2, 4, StringComparison.Ordinal));

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

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

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

// The example displays the following output:
//       4
//       3
//       3
//       -1
Module Example
   Public Sub Main()
      Dim searchString As String = Chrw(&h00AD) + "m"
      Dim s1 As String = "ani" + ChrW(&h00AD) + "mal"
      Dim s2 As String = "animal"

      Console.WriteLine(s1.IndexOf(searchString, 2, 4, StringComparison.CurrentCulture))
      Console.WriteLine(s1.IndexOf(searchString, 2, 4, StringComparison.Ordinal))
      Console.WriteLine(s2.IndexOf(searchString, 2, 4, StringComparison.CurrentCulture))
      Console.WriteLine(s2.IndexOf(searchString, 2, 4, StringComparison.Ordinal))
   End Sub
End Module
' The example displays the following output:
'       4
'       3
'       3
'       -1

适用于

IndexOf(String, Int32, StringComparison)

报告指定的字符串在当前 String 对象中的第一个匹配项的从零开始的索引。 参数指定当前字符串中的起始搜索位置以及用于指定字符串的搜索类型。

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

参数

value
String

要搜寻的字符串。

startIndex
Int32

搜索起始位置。

comparisonType
StringComparison

指定搜索规则的枚举值之一。

返回

如果找到该字符串,则为从当前实例的起始位置开始的从零开始的 value 参数索引位置;否则为 -1。 如果 valueEmpty,则返回值为 startIndex

例外

valuenull

startIndex 小于 0(零)或大于此字符串的长度。

comparisonType 不是有效的 StringComparison 值。

示例

下面的示例演示 方法的 IndexOf 三个重载,这些重载使用 枚举的不同值 StringComparison 在另一个字符串中查找字符串的第一个匹配项。

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

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

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the first occurrence of a character using different " + 
                   "values of StringComparison.";
    string resultFmt = "Comparison: {0,-28} Location: {1,3}";

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

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

    int loc = 0;
    StringComparison[] scValues = {
        StringComparison.CurrentCulture,
        StringComparison.CurrentCultureIgnoreCase,
        StringComparison.InvariantCulture,
        StringComparison.InvariantCultureIgnoreCase,
        StringComparison.Ordinal,
        StringComparison.OrdinalIgnoreCase };

// Clear the screen and display an introduction.
    Console.Clear();
    Console.WriteLine(intro);

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

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    Console.WriteLine("The current culture is \"{0}\" - {1}.", 
                       Thread.CurrentThread.CurrentCulture.Name,
                       Thread.CurrentThread.CurrentCulture.DisplayName);

// Display the string to search for and the string to search.
    Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"", 
                       CapitalAWithRing, cat);
    Console.WriteLine();

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

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

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

// Search using different values of StringComparison. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(CapitalAWithRing, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }
    }
}

/*
Note: This code example was executed on a console whose user interface 
culture is "en-US" (English-United States).

This code example produces the following results:

Find the first occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

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

open System
open System.Threading
open System.Globalization

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

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

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

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

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

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

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

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

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

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

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

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

(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).

This code example produces the following results:

Find the first occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

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

Imports System.Threading
Imports System.Globalization

Class Sample
    Public Shared Sub Main() 
        Dim intro As String = "Find the first occurrence of a character using different " & _
                              "values of StringComparison."
        Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
        
        ' Define a string to search for.
        ' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
        Dim CapitalAWithRing As String = "Å"
        
        ' Define a string to search. 
        ' The result of combining the characters LATIN SMALL LETTER A and COMBINING 
        ' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character 
        ' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
        Dim cat As String = "A Cheshire c" & "å" & "t"
        
        Dim loc As Integer = 0
        Dim scValues As StringComparison() =  { _
                        StringComparison.CurrentCulture, _
                        StringComparison.CurrentCultureIgnoreCase, _
                        StringComparison.InvariantCulture, _
                        StringComparison.InvariantCultureIgnoreCase, _
                        StringComparison.Ordinal, _
                        StringComparison.OrdinalIgnoreCase }
        Dim sc As StringComparison
        
        ' Clear the screen and display an introduction.
        Console.Clear()
        Console.WriteLine(intro)
        
        ' Display the current culture because culture affects the result. For example, 
        ' try this code example with the "sv-SE" (Swedish-Sweden) culture.
        Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
        Console.WriteLine("The current culture is ""{0}"" - {1}.", _
                           Thread.CurrentThread.CurrentCulture.Name, _ 
                           Thread.CurrentThread.CurrentCulture.DisplayName)
        
        ' Display the string to search for and the string to search.
        Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
                           CapitalAWithRing, cat)
        Console.WriteLine()
        
        ' Note that in each of the following searches, we look for 
        ' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains 
        ' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates 
        ' the string was not found.
        ' Search using different values of StringComparison. Specify the start 
        ' index and count.

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

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

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

'
'Note: This code example was executed on a console whose user interface 
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the first occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'

注解

索引编号从 0 开始。 startIndex 参数可以介于 0 到字符串实例的长度。 如果 startIndex 等于字符串实例的长度,则该方法返回 -1。

参数 comparisonType 指定使用当前或固定区域性、使用区分大小写或不区分大小写的搜索以及使用单词或序号比较规则来搜索 value 参数。

调用方说明

字符集包括可忽略字符,在执行语言性的或区分区域性的比较时该字符不被考虑。 在区分区域性的搜索 (即,如果 comparisonType 不是 OrdinalOrdinalIgnoreCase) 中,如果 value 包含一个可忽略字符,则结果与移除了该字符的搜索等效。 如果 value 仅包含一个或多个可忽略字符,则 IndexOf(String, Int32, StringComparison) 该方法始终返回 startIndex,即搜索开始处的字符位置。

在下面的示例中, IndexOf(String, Int32, StringComparison) 方法用于查找软连字符的位置 (U+00AD) 后跟一个“m”,该位置从两个字符串中的第三个字符位置开始。 只有一个字符串包含必需的子字符串。 如果示例在 .NET Framework 4 或更高版本上运行,在这两种情况下,由于软连字符是可忽略的字符,则该方法在执行区分区域性的比较时,会返回字符串中“m”的索引。 注意对于第一个字符串,包含软连字符后跟“m”,该方法无法返回该软连字符的索引,而是返回“m”的索引。 只有当此方法执行序号比较时,它才会在第一个字符串中返回软连字符的索引。

using System;

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

        Console.WriteLine(s1.IndexOf(searchString, 2, StringComparison.CurrentCulture));
        Console.WriteLine(s1.IndexOf(searchString, 2, StringComparison.Ordinal));
        Console.WriteLine(s2.IndexOf(searchString, 2, StringComparison.CurrentCulture));
        Console.WriteLine(s2.IndexOf(searchString, 2, StringComparison.Ordinal));

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

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

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

// The example displays the following output:
//       4
//       3
//       3
//       -1
Module Example
   Public Sub Main()
      Dim searchString As String = Chrw(&h00AD) + "m"
      Dim s1 As String = "ani" + ChrW(&h00AD) + "mal"
      Dim s2 As String = "animal"

      Console.WriteLine(s1.IndexOf(searchString, 2, StringComparison.CurrentCulture))
      Console.WriteLine(s1.IndexOf(searchString, 2, StringComparison.Ordinal))
      Console.WriteLine(s2.IndexOf(searchString, 2, StringComparison.CurrentCulture))
      Console.WriteLine(s2.IndexOf(searchString, 2, StringComparison.Ordinal))
   End Sub
End Module
' The example displays the following output:
'       4
'       3
'       3
'       -1

适用于

IndexOf(String, StringComparison)

报告指定的字符串在当前 String 对象中的第一个匹配项的从零开始的索引。 一个参数指定要用于指定字符串的搜索类型。

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

参数

value
String

要搜寻的字符串。

comparisonType
StringComparison

指定搜索规则的枚举值之一。

返回

如果找到该字符串,则为 value 参数的索引位置;如果未找到该字符串,则为 -1。 如果 valueEmpty,则返回值为 0。

例外

valuenull

comparisonType 不是有效的 StringComparison 值。

示例

下面的示例演示 方法的 IndexOf 三个重载,这些重载使用 枚举的不同值 StringComparison 在另一个字符串中查找字符串的第一个匹配项。

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

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

class Sample 
{
    public static void Main() 
    {
    string intro = "Find the first occurrence of a character using different " + 
                   "values of StringComparison.";
    string resultFmt = "Comparison: {0,-28} Location: {1,3}";

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

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

    int loc = 0;
    StringComparison[] scValues = {
        StringComparison.CurrentCulture,
        StringComparison.CurrentCultureIgnoreCase,
        StringComparison.InvariantCulture,
        StringComparison.InvariantCultureIgnoreCase,
        StringComparison.Ordinal,
        StringComparison.OrdinalIgnoreCase };

// Clear the screen and display an introduction.
    Console.Clear();
    Console.WriteLine(intro);

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

    Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    Console.WriteLine("The current culture is \"{0}\" - {1}.", 
                       Thread.CurrentThread.CurrentCulture.Name,
                       Thread.CurrentThread.CurrentCulture.DisplayName);

// Display the string to search for and the string to search.
    Console.WriteLine("Search for the string \"{0}\" in the string \"{1}\"", 
                       CapitalAWithRing, cat);
    Console.WriteLine();

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

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

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

// Search using different values of StringComparison. 
    Console.WriteLine("\nPart 3: Neither start index nor count is specified.");
    foreach (StringComparison sc in scValues)
        {
        loc = cat.IndexOf(CapitalAWithRing, sc);
        Console.WriteLine(resultFmt, sc, loc);
        }
    }
}

/*
Note: This code example was executed on a console whose user interface 
culture is "en-US" (English-United States).

This code example produces the following results:

Find the first occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

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

open System
open System.Threading
open System.Globalization

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

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

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

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

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

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

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

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

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

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

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

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

(*
Note: This code example was executed on a console whose user interface
culture is "en-US" (English-United States).

This code example produces the following results:

Find the first occurrence of a character using different values of StringComparison.
The current culture is "en-US" - English (United States).
Search for the string "Å" in the string "A Cheshire ca°t"

Part 1: Start index and count are specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 2: Start index is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

Part 3: Neither start index nor count is specified.
Comparison: CurrentCulture               Location:  -1
Comparison: CurrentCultureIgnoreCase     Location:  12
Comparison: InvariantCulture             Location:  -1
Comparison: InvariantCultureIgnoreCase   Location:  12
Comparison: Ordinal                      Location:  -1
Comparison: OrdinalIgnoreCase            Location:  -1

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

Imports System.Threading
Imports System.Globalization

Class Sample
    Public Shared Sub Main() 
        Dim intro As String = "Find the first occurrence of a character using different " & _
                              "values of StringComparison."
        Dim resultFmt As String = "Comparison: {0,-28} Location: {1,3}"
        
        ' Define a string to search for.
        ' U+00c5 = LATIN CAPITAL LETTER A WITH RING ABOVE
        Dim CapitalAWithRing As String = "Å"
        
        ' Define a string to search. 
        ' The result of combining the characters LATIN SMALL LETTER A and COMBINING 
        ' RING ABOVE (U+0061, U+030a) is linguistically equivalent to the character 
        ' LATIN SMALL LETTER A WITH RING ABOVE (U+00e5).
        Dim cat As String = "A Cheshire c" & "å" & "t"
        
        Dim loc As Integer = 0
        Dim scValues As StringComparison() =  { _
                        StringComparison.CurrentCulture, _
                        StringComparison.CurrentCultureIgnoreCase, _
                        StringComparison.InvariantCulture, _
                        StringComparison.InvariantCultureIgnoreCase, _
                        StringComparison.Ordinal, _
                        StringComparison.OrdinalIgnoreCase }
        Dim sc As StringComparison
        
        ' Clear the screen and display an introduction.
        Console.Clear()
        Console.WriteLine(intro)
        
        ' Display the current culture because culture affects the result. For example, 
        ' try this code example with the "sv-SE" (Swedish-Sweden) culture.
        Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
        Console.WriteLine("The current culture is ""{0}"" - {1}.", _
                           Thread.CurrentThread.CurrentCulture.Name, _ 
                           Thread.CurrentThread.CurrentCulture.DisplayName)
        
        ' Display the string to search for and the string to search.
        Console.WriteLine("Search for the string ""{0}"" in the string ""{1}""", _
                           CapitalAWithRing, cat)
        Console.WriteLine()
        
        ' Note that in each of the following searches, we look for 
        ' LATIN CAPITAL LETTER A WITH RING ABOVE in a string that contains 
        ' LATIN SMALL LETTER A WITH RING ABOVE. A result value of -1 indicates 
        ' the string was not found.
        ' Search using different values of StringComparison. Specify the start 
        ' index and count.

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

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

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

'
'Note: This code example was executed on a console whose user interface 
'culture is "en-US" (English-United States).
'
'This code example produces the following results:
'
'Find the first occurrence of a character using different values of StringComparison.
'The current culture is "en-US" - English (United States).
'Search for the string "Å" in the string "A Cheshire ca°t"
'
'Part 1: Start index and count are specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'
'Part 2: Start index is specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'
'Part 3: Neither start index nor count is specified.
'Comparison: CurrentCulture               Location:  -1
'Comparison: CurrentCultureIgnoreCase     Location:  12
'Comparison: InvariantCulture             Location:  -1
'Comparison: InvariantCultureIgnoreCase   Location:  12
'Comparison: Ordinal                      Location:  -1
'Comparison: OrdinalIgnoreCase            Location:  -1
'

注解

索引编号从零开始。

参数 comparisonType 指定使用当前或固定区域性、使用区分大小写或不区分大小写的搜索以及使用单词或序号比较规则来搜索 value 参数。

调用方说明

字符集包括可忽略字符,在执行语言性的或区分区域性的比较时该字符不被考虑。 在区分区域性的搜索 (即,如果 comparisonType 不是 OrdinalOrdinalIgnoreCase) 中,如果 value 包含一个可忽略字符,则结果与移除了该字符的搜索等效。 如果 value 仅包含一个或多个可忽略字符,则 IndexOf(String, StringComparison) 该方法始终返回 0 (零) 以指示在当前实例的开头找到匹配项。

在以下示例中, IndexOf(String, StringComparison) 方法用于查找三个子字符串, (一个软连字符 (U+00AD) 、一个后跟“n”的软连字符和一个后跟“m”) 的软连字符。 只有一个字符串包含软连字符。 如果在.NET Framework 4 或更高版本上运行该示例,由于软连字符是可忽略的字符,则区分区域性的搜索返回的值与搜索字符串中未包含软连字符时返回的值相同。 但是,序号搜索在一个字符串中成功找到软连字符,并报告第二个字符串中不存在该连字符。

using System;

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

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

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

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

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

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

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

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

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

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

适用于

IndexOf(Char, Int32, Int32)

报告指定字符在此实例中的第一个匹配项的从零开始的索引。 搜索从指定字符位置开始,并检查指定数量的字符位置。

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

参数

value
Char

要查找的 Unicode 字符。

startIndex
Int32

搜索起始位置。

count
Int32

要检查的字符位置数。

返回

如果找到该字符,则为从字符串的起始位置开始的 value 从零开始的索引位置;否则为 -1。

例外

countstartIndex 为负数。

startIndex 大于此字符串的长度。

count 大于此字符串的长度减 startIndex

示例

下面的示例演示 IndexOf 方法。

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

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

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

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

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

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

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

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

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

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

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

        int     startIndex = -1;
        int     hitCount = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

    printfn $"occurrences: {hitCount}"

findAllChar 'A' str
findAllChar 'a' str
findAllChar 'I' str
findAllChar 'i' str
findAllChar '@' str
findAllChar ' ' str


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

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

The character 'A' occurs at position(s): 0, 20, 40, 60, occurrences: 4
The character 'a' occurs at position(s): 10, 30, 50, occurrences: 3
The character 'I' occurs at position(s): 8, 28, 48, 68, occurrences: 4
The character 'i' occurs at position(s): 18, 38, 58, occurrences: 3
The character '@' occurs at position(s): occurrences: 0
The character ' ' occurs at position(s): 9, 19, 29, 39, 49, 59, occurrences: 6
*)
' Example for the String.IndexOf( Char, Integer, Integer ) method.
Module IndexOfCII
   
    Sub Main()
        Dim br1 As String = _
            "0----+----1----+----2----+----3----+----" & _
            "4----+----5----+----6----+----7"
        Dim br2 As String = _
            "0123456789012345678901234567890123456789" & _
            "0123456789012345678901234567890"
        Dim str As String = _
            "ABCDEFGHI abcdefghi ABCDEFGHI abcdefghi " & _
            "ABCDEFGHI abcdefghi ABCDEFGHI"
          
        Console.WriteLine( _
            "This example of String.IndexOf( Char, Integer, Integer )" & _
            vbCrLf & "generates the following output." )
        Console.WriteLine( _
            "{0}{1}{0}{2}{0}{3}{0}", _
            Environment.NewLine, br1, br2, str)

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

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

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

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

    End Sub
End Module 'IndexOfCII

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

注解

搜索从 开始 startIndex ,继续为 startIndex + count -1。 在 startIndex + count 的字符不包括在搜索中。

索引编号从 0 开始 (零) 。 startIndex 参数可以介于 0 到字符串实例的长度。

此方法执行不区分区域性的序号 () 搜索,其中仅当一个字符的 Unicode 标量值相同时,才认为该字符等效于另一个字符。 若要执行区分区域性的搜索,请使用 CompareInfo.IndexOf 方法,其中表示预分解字符的 Unicode 标量值(如连字“Æ” (U+00C6) )可能被视为等效于字符组件在正确序列中的任何匹配项,例如“AE” (U+0041、U+0045) ,具体取决于区域性。

另请参阅

适用于

IndexOf(Char, StringComparison)

报告指定 Unicode 字符在此字符串中的第一个匹配项的从零开始的索引。 一个参数指定要用于指定字符的搜索类型。

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

参数

value
Char

要查找的字符。

comparisonType
StringComparison

指定搜索规则的枚举值。

返回

如果找到该字符,则为 value 的从零开始的索引位置;如果未找到,则为 -1。

例外

comparisonType 不是有效的 StringComparison 值。

注解

索引编号从零开始。

参数 comparisonType 是一个 StringComparison 枚举成员,指定搜索参数是 value 使用当前区域性还是固定区域性、区分大小写或不区分大小写,还是使用单词或序号比较规则。

适用于

IndexOf(Char, Int32)

报告指定 Unicode 字符在此字符串中的第一个匹配项的从零开始的索引。 该搜索从指定字符位置开始。

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

参数

value
Char

要查找的 Unicode 字符。

startIndex
Int32

搜索起始位置。

返回

如果找到该字符,则为从字符串的起始位置开始的 value 从零开始的索引位置;否则为 -1。

例外

startIndex 小于 0(零)或大于此字符串的长度。

示例

下面的示例演示 IndexOf 方法。

// Sample for String::IndexOf(Char, Int32)
using namespace System;
int main()
{
   String^ br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
   String^ br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
   String^ str = "Now is the time for all good men to come to the aid of their party.";
   int start;
   int at;
   Console::WriteLine();
   Console::WriteLine( "All occurrences of 't' from position 0 to {0}.", str->Length - 1 );
   Console::WriteLine( "{1}{0}{2}{0}{3}{0}", Environment::NewLine, br1, br2, str );
   Console::Write( "The letter 't' occurs at position(s): " );
   at = 0;
   start = 0;
   while ( (start < str->Length) && (at > -1) )
   {
      at = str->IndexOf( 't', start );
      if ( at == -1 )
            break;

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

   Console::WriteLine();
}

/*
This example produces the following results:

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

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

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

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

at = 0;
start = 0;
while((start < str.Length) && (at > -1))
{
    at = str.IndexOf('t', start);
    if (at == -1) break;
    Console.Write("{0} ", at);
    start = at+1;
}
Console.WriteLine();

/*
This example produces the following results:

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

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

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

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

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

(*
This example produces the following results:

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

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

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

Module Sample
    Sub Main()

        Dim br1 As String = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-"
        Dim br2 As String = "0123456789012345678901234567890123456789012345678901234567890123456"
        Dim str As String = "Now is the time for all good men to come to the aid of their party."
        Dim start As Integer
        Dim at As Integer

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

        at = 0
        start = 0
        While start < str.Length AndAlso at > -1
            at = str.IndexOf("t"c, start)
            If at = -1 Then
                Exit While
            End If
            Console.Write("{0} ", at)
            start = at + 1
        End While
        Console.WriteLine()
    End Sub
End Module
'
'This example produces the following results:
'
'All occurrences of 't' from position 0 to 66.
'0----+----1----+----2----+----3----+----4----+----5----+----6----+-
'0123456789012345678901234567890123456789012345678901234567890123456
'Now is the time for all good men to come to the aid of their party.
'
'The letter 't' occurs at position(s): 7 11 33 41 44 55 64
'
'

注解

索引编号从 0 开始。 startIndex 参数可以介于 0 到字符串实例的长度。 如果 startIndex 等于字符串实例的长度,则该方法返回 -1。

搜索范围从 startIndex 到字符串的末尾。

此方法执行不区分区域性的序号 () 搜索,其中仅当一个字符的 Unicode 标量值相同时,才认为该字符等效于另一个字符。 若要执行区分区域性的搜索,请使用 CompareInfo.IndexOf 方法,其中表示预分解字符的 Unicode 标量值(如连字“Æ” (U+00C6) )可能被视为等效于字符组件在正确序列中的任何匹配项,例如“AE” (U+0041、U+0045) ,具体取决于区域性。

另请参阅

适用于

IndexOf(String)

报告指定字符串在此实例中的第一个匹配项的从零开始的索引。

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

参数

value
String

要搜寻的字符串。

返回

如果找到该字符串,则为 value 的从零开始的索引位置;如果未找到该字符串,则为 -1。 如果 valueEmpty,则返回值为 0。

例外

valuenull

示例

以下示例在“animal”中搜索“n”。 由于字符串索引从零开始而不是从 1 开始,因此 该方法 IndexOf(String) 指示“n”位于位置 1。

using namespace System;

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

}
// The example displays the following output:
//        Found 'n' in 'animal' at position 1
String str = "animal";
String toFind = "n";
int index = str.IndexOf("n");
Console.WriteLine("Found '{0}' in '{1}' at position {2}",
                toFind, str, index);

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

let str = "animal"
let toFind = "n"
let index = str.IndexOf "n"
printfn $"Found '{toFind}' in '{str}' at position {index}"

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

以下示例使用 IndexOf 方法确定动物名称在句子中的起始位置。 然后,它使用此位置在句子中插入描述动物的形容词。

using namespace System;

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

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

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

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

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

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

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

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

        Console.WriteLine("{0}The final string is:{0}{1}",
                          Environment.NewLine, strTarget);
    }
}
// Output from the example might appear as follows:
//       The original string is:
//       The fox jumps over the dog.
//
//       Enter an adjective (or group of adjectives) to describe the fox: ==> bold
//       Enter an adjective (or group of adjectives) to describe the dog: ==> lazy
//
//       The final string is:
//       The bold fox jumps over the lazy dog.
open System

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

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

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

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

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

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

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

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

注解

索引编号从零开始。

此方法使用当前区域性执行单词 (区分大小写和区分区域性) 搜索。 搜索从此实例的第一个字符位置开始,一直持续到最后一个字符位置。

字符集包括可忽略字符,在执行语言性的或区分区域性的比较时该字符不被考虑。 在区分区域性的搜索中,如果 value 包含一个可忽略字符,则结果与移除了该字符的搜索等效。 如果 value 仅包含一个或多个可忽略字符,则 IndexOf(String) 该方法始终返回 0 (零) 以指示在当前实例的开头找到匹配项。 在以下示例中, IndexOf(String) 方法用于查找三个子字符串, (一个软连字符 (U+00AD) 、一个后跟“n”的软连字符和一个后跟“m”) 的软连字符。 只有一个字符串包含软连字符。 如果在.NET Framework 4 或更高版本上运行该示例,则在每个情况下,由于软连字符是可忽略的字符,结果与软连字符未包含在 中value一样。 仅搜索软连字符时,该方法返回 0 (零) ,以指示它已找到字符串开头的匹配项。

using System;

public class Example
{
    public static void Main()
    {
        string s1 = "ani\u00ADmal";
        string s2 = "animal";
      
        // Find the index of the soft hyphen.
        Console.WriteLine(s1.IndexOf("\u00AD"));
        Console.WriteLine(s2.IndexOf("\u00AD"));
      
        // Find the index of the soft hyphen followed by "n".
        Console.WriteLine(s1.IndexOf("\u00ADn"));
        Console.WriteLine(s2.IndexOf("\u00ADn"));
      
        // Find the index of the soft hyphen followed by "m".
        Console.WriteLine(s1.IndexOf("\u00ADm"));
        Console.WriteLine(s2.IndexOf("\u00ADm"));

        // The example displays the following output
        // if run under the .NET Framework 4 or later:
        //       0
        //       0
        //       1
        //       1
        //       4
        //       3
    }
}
let s1 = "ani\u00ADmal"
let s2 = "animal"

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

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

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

// The example displays the following output
// if run under the .NET Framework 4 or later:
//       0
//       0
//       1
//       1
//       4
//       3
Module Example
   Public Sub Main()
      Dim softHyphen As String = ChrW(&h00AD)
      Dim s1 As String = "ani" + softHyphen + "mal"
      Dim s2 As String = "animal"
      
      ' Find the index of the soft hyphen.
      Console.WriteLine(s1.IndexOf(softHyphen))
      Console.WriteLine(s2.IndexOf(softHyphen))
      
      ' Find the index of the soft hyphen followed by "n".
      Console.WriteLine(s1.IndexOf(softHyphen + "n"))
      Console.WriteLine(s2.IndexOf(softHyphen + "n"))
      
      ' Find the index of the soft hyphen followed by "m".
      Console.WriteLine(s1.IndexOf(softHyphen + "m"))
      Console.WriteLine(s2.IndexOf(softHyphen + "m"))
   End Sub
End Module
' The example displays the following output 
' if run under the .NET Framework 4 or later:
'       0
'       0
'       1
'       1
'       4
'       3

调用方说明

使用字符串的最佳做法中所述,建议避免调用替换默认值的字符串比较方法,而是调用需要显式指定参数的方法。 若要使用当前区域性的比较规则在字符串实例中查找子字符串的第一个索引,请通过为其参数调用值为 CurrentCulturecomparisonType 的方法重载来显式发出IndexOf(String, StringComparison)信号。 如果不需要语言感知比较,请考虑使用 Ordinal

另请参阅

适用于

IndexOf(Char)

报告指定 Unicode 字符在此字符串中的第一个匹配项的从零开始的索引。

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

参数

value
Char

要查找的 Unicode 字符。

返回

如果找到该字符,则为 value 的从零开始的索引位置;如果未找到,则为 -1。

示例

以下示例演示如何使用 IndexOf 方法搜索 String 字符。

using namespace System;

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

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

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

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

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

   Console::WriteLine("First occurrence of the Greek letter Alpha: Index {0}", 
                      ialpha);
   Console::WriteLine("First occurrence of the Greek letter Omega: Index {0}", 
                      iomega);
}
// The example displays the following output:
//       The string: OOO?????OOO
//       First occurrence of the Greek letter Alpha: Index 3
//       First occurrence of the Greek letter Omega: Index 0
// Create a Unicode string with 5 Greek Alpha characters.
String szGreekAlpha = new String('\u0391',5);

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

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

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

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

Console.WriteLine("First occurrence of the Greek letter Alpha: Index {0}", 
                ialpha);
Console.WriteLine("First occurrence of the Greek letter Omega: Index {0}", 
                iomega);

// The example displays the following output:
//    The string: ΩΩΩΑΑΑΑΑΩΩΩ
//    First occurrence of the Greek letter Alpha: Index 3
//    First occurrence of the Greek letter Omega: Index 0
open System

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

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

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

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

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

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

// The example displays the following output:
//    The string: ΩΩΩΑΑΑΑΑΩΩΩ
//    First occurrence of the Greek letter Alpha: Index 3
//    First occurrence of the Greek letter Omega: Index 0
Public Module Example
   Public Sub Main()
      ' Create a Unicode string with 5 Greek Alpha characters.
      Dim szGreekAlpha As New String(ChrW(&H0391), 5)

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

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

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

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

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

注解

索引编号从零开始。

此方法执行不区分区域性的序号 () 搜索,其中仅当一个字符的 Unicode 标量值相同时,才认为该字符等效于另一个字符。 若要执行区分区域性的搜索,请使用 CompareInfo.IndexOf 方法,其中表示预分解字符的 Unicode 标量值(如连字“Æ” (U+00C6) )可能被视为等效于字符组件在正确序列中的任何匹配项,例如“AE” (U+0041、U+0045) ,具体取决于区域性。

另请参阅

适用于

IndexOf(String, Int32)

报告指定字符串在此实例中的第一个匹配项的从零开始的索引。 该搜索从指定字符位置开始。

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

参数

value
String

要搜寻的字符串。

startIndex
Int32

搜索起始位置。

返回

如果找到该字符串,则为从当前实例的起始位置开始的从零开始的 value 的索引位置;否则为 -1。 如果 valueEmpty,则返回值为 startIndex

例外

valuenull

startIndex 小于 0(零)或大于此字符串的长度。

示例

以下示例在目标字符串中搜索指定字符串的所有匹配项。

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

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

public class IndexOfTest {
    public static void Main() {

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

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

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

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

            strTarget = Console.ReadLine();

            if (strTarget != "") {

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

                    found = strSource.IndexOf(strTarget, i);

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

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

            totFinds = 0;
        } while ( true );
    }
}
open System

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

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

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

    let strTarget = stdin.ReadLine()

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

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

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

注解

索引编号从 0 开始。 startIndex 参数可以介于 0 到字符串实例的长度。 如果 startIndex 等于字符串实例的长度,则该方法返回 -1。

此方法使用当前区域性执行单词 (区分大小写和区分区域性) 搜索。 搜索从此实例的 startIndex 字符位置开始,一直持续到最后一个字符位置。

字符集包括可忽略字符,在执行语言性的或区分区域性的比较时该字符不被考虑。 在区分区域性的搜索中,如果 value 包含一个可忽略字符,则结果与移除了该字符的搜索等效。 如果 value 仅包含一个或多个可忽略字符,则 IndexOf(String, Int32) 该方法始终返回 startIndex,即搜索开始处的字符位置。 在下面的示例中, IndexOf(String, Int32) 方法用于查找软连字符的位置, (U+00AD) 后跟两个字符串中的“m”。 只有一个字符串包含必需的子字符串。 如果在.NET Framework 4 或更高版本上运行该示例,在这两种情况下,由于软连字符是可忽略的字符,则 该方法在字符串中返回“m”的索引。 注意对于第一个字符串,包含软连字符后跟“m”,该方法无法返回该软连字符的索引,而是返回“m”的索引。

using System;

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

        Console.WriteLine(s1.IndexOf(searchString, 2));
        Console.WriteLine(s2.IndexOf(searchString, 2));

        // The example displays the following output:
        //       4
        //       3
    }
}
let searchString = "\u00ADm"
let s1 = "ani\u00ADmal"
let s2 = "animal"

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

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

      Console.WriteLine(s1.IndexOf(searchString, 2))
      Console.WriteLine(s2.IndexOf(searchString, 2))
   End Sub
End Module
' The example displays the following output:
'       4
'       3

调用方说明

使用字符串的最佳做法中所述,建议避免调用替换默认值的字符串比较方法,而是调用需要显式指定参数的方法。 若要使用当前区域性的比较规则查找在特定字符位置之后发生的子字符串的第一个索引,请通过调用IndexOf(String, Int32, StringComparison)方法重载(其comparisonType参数的 CurrentCulture 值为 )来明确表示你的意图。 如果不需要语言感知比较,请考虑使用 Ordinal

另请参阅

适用于