System.String.LastIndexOf 方法 (Char, Int32)

方法描述

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

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

public int LastIndexOf(
	char value,
	int startIndex
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
value System-Char 要查找的 Unicode 字符。
startIndex System-Int32 此实例内子字符串的起始位置。
返回值 System.Int32 如果找到该字符,则为 value 的从零开始的索引位置;如果未找到,则为 -1。或者如果当前实例等于 String.Empty 则也为 -1。

提示和注释

索引编号从零开始。 也就是说,字符串中第一个字符的位置为索引 0,而最后一个字符的位置为 Length - 1。此方法从该实例的 startIndex 字符位置开始,沿反向向前搜索,直到找到 value 或检查完第一个字符位置为止。 例如,如果 startIndex 为 Length - 1,则该方法将搜索从字符串中最后一个字符到开头的所有字符。 该搜索区分大小写。

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

System.String.LastIndexOf 方法 (Char, Int32)例子

下面的示例从某个字符串的末尾到开头查找该字符串中某一字符的所有匹配项的索引。

// Sample for String.LastIndexOf(Char, Int32)
using System;

class Sample {
    public static void Main() {

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

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

    at = 0;
    while((start > -1) && (at > -1))
        {
        at = str.LastIndexOf('t', start);
        if (at > -1) 
            {
            Console.Write("{0} ", at);
            start = at - 1;
            }
        }
    Console.Write("{0}{0}{0}", Environment.NewLine);
    }
}
/*
This example produces the following results:
All occurrences of 't' from position 66 to 0.
0----+----1----+----2----+----3----+----4----+----5----+----6----+-
0123456789012345678901234567890123456789012345678901234567890123456
Now is the time for all good men to come to the aid of their party.

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

异常

异常 异常描述
ArgumentOutOfRangeException 当前实例不等于 String.Empty,而且 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 系统要求。