System.String.IndexOfAny 方法 (Char[], Int32, Int32)

方法描述

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

语法定义(C# System.String.IndexOfAny 方法 (Char[], Int32, Int32) 的用法)

public int IndexOfAny(
	char[] anyOf,
	int startIndex,
	int count
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
anyOf System-Char[] Unicode 字符数组,包含一个或多个要查找的字符。
startIndex System-Int32 搜索起始位置。
count System-Int32 要检查的字符位置数。
返回值 System.Int32 在此实例中第一次找到 anyOf 中的任意字符的索引位置(从零开始);如果未找到 anyOf 中的字符,则为 -1。

提示和注释

搜索从 startIndex 开始,并且一直搜索至 startIndex + count -1。 startIndex + count 位置上的字符不在搜索范围内。

索引编号从零开始。 startIndex 参数的范围可以从 0 到字符串实例的长度减一。

对 anyOf 的搜索区分大小写。

此方法执行顺序(不区分区域性)搜索,即,仅当 Unicode 标量值相同时两个字符才被视为相等。 若要执行区分区域性的搜索,请使用 CompareInfo.IndexOf 方法,根据所使用的区域性,该方法可能将表示预先构成字符(如连字“Æ”(U+00C6))的 Unicode 标量值视为等同于任何顺序正确的该字符的组成字符,如上述连字可能被视为“AE”(U+0041、U+0045)。

System.String.IndexOfAny 方法 (Char[], Int32, Int32)例子

下面的示例查找字符串“aid”的任意字符在另一个字符串的子字符串中的匹配项的索引。

// Sample for String.IndexOfAny(Char[], Int32, Int32)
using System;

class Sample {
    public static void Main() 
    {
    string br1 = "0----+----1----+----2----+----3----+----4----+----5----+----6----+-";
    string br2 = "0123456789012345678901234567890123456789012345678901234567890123456";
    string str = "Now is the time for all good men to come to the aid of their party.";
    int start;
    int at;
    int count;
    string target = "aid";
    char[] anyOf = target.ToCharArray();

    start = (str.Length-1)/3;
    count = (str.Length-1)/4;
    Console.WriteLine();
    Console.WriteLine("The first character occurrence from position {0} for {1} characters.", start, count);
    Console.WriteLine("{1}{0}{2}{0}{3}{0}", Environment.NewLine, br1, br2, str);
    Console.Write("A character in '{0}' occurs at position: ", target);

    at = str.IndexOfAny(anyOf, start, count);
    if (at > -1) 
        Console.Write(at);
    else
        Console.Write("(not found)");
    Console.WriteLine();
    }
}
/*

The first character occurrence from position 22 for 16 characters.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

A character in 'aid' occurs at position: 27

*/

异常

异常 异常描述
ArgumentNullException anyOf 为 null。
ArgumentOutOfRangeException
  • count 或 startIndex 为负。
  • count+startIndex 大于此实例中的字符数。

命名空间

namespace: System

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。