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

方法描述

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

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

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

参数/返回值

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

提示和注释

索引编号从零开始。

此方法从该实例的 startIndex 字符位置开始,沿反向向前搜索,直到找到 anyOf 中的字符或已检查了 count 个字符位置。 该搜索区分大小写。

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

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

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

// Sample for String.LastIndexOfAny(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)*2)/3;
    count = (str.Length-1)/3;
    Console.WriteLine("The last 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.LastIndexOfAny(anyOf, start, count);
    if (at > -1) 
        Console.Write(at);
    else
        Console.Write("(not found)");
    Console.Write("{0}{0}{0}", Environment.NewLine);
    }
}
/*
This example produces the following results:
The last character occurrence from position 44 for 22 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
  • 当前实例不等于 String.Empty,且 count 或 startIndex 是负数。
  • 当前实例不等于 String.Empty,而且 startIndex 减去 count 指定一个不在此实例中的位置。

命名空间

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 系统要求。