System.String.LastIndexOf 方法 (String)

方法描述

报告指定字符串在此实例中的最后一个匹配项的索引位置。

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

public int LastIndexOf(
	string value
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
value System-String 要搜寻的字符串。
返回值 System.Int32 如果找到该字符串,则为 value 的从零开始的索引位置;如果未找到该字符串,则为 -1。 如果 value 为 String.Empty,则为此实例中的最后一个索引位置。

提示和注释

索引编号从零开始。 也就是说,字符串中第一个字符的位置为索引 0,而最后一个字符的位置为 Length - 1。

搜索从该实例的最后一个字符位置开始,沿反向向前搜索,直到找到 value 或检查完第一个字符位置为止。

此方法使用当前区域性执行单词(区分大小写和区域性)搜索。

对调用者的说明

如 在 .NET Framework 中使用字符串的最佳做法 中所述,我们建议您避免调用替换默认值的字符串比较方法,而是调用需要显式指定参数的方法。 若要使用当前区域性的比较规则查找在字符串实例内某个子字符串的最后一个索引,请为它的 comparisonType 参数使用 StringComparison.CurrentCulture 的值调用 LastIndexOf(String, StringComparison) 方法重载。

System.String.LastIndexOf 方法 (String)例子

如果字符串以右括号字符 (">") 结束,则示例使用 LastIndexOf 方法来查找结束标记的开头。

using System;

public class Example 
{
   public static void Main() 
   {
      string[] strSource = { "This is bold text", "

This is large Text

", "This has multiple tags", "This has embedded tags.", "This line ends with a greater than symbol and should not be modified>" }; // Strip HTML start and end tags from each string if they are present. foreach (string s in strSource) { Console.WriteLine("Before: " + s); string item = s; // Use EndsWith to find a tag at the end of the line. if (item.Trim().EndsWith(">")) { // Locate the opening tag. int endTagStartPosition = item.LastIndexOf("= 0 ) item = item.Substring(0, endTagStartPosition); // Use StartsWith to find the opening tag. if (item.Trim().StartsWith("<")) { // Locate the end of opening tab. int openTagEndPosition = item.IndexOf(">"); // Remove the identified section, if it is valid. if (openTagEndPosition >= 0) item = item.Substring(openTagEndPosition + 1); } } // Display the trimmed string. Console.WriteLine("After: " + item); Console.WriteLine(); } } } // The example displays the following output: // Before: This is bold text // After: This is bold text // // Before:

This is large Text

// After: This is large Text // // Before: This has multiple tags // After: This has multiple tags // // Before: This has embedded tags. // After: This has embedded tags. // // Before: This line ends with a greater than symbol and should not be modified> // After: This line ends with a greater than symbol and should not be modified>

异常

异常 异常描述
ArgumentNullException value 为 null。

命名空间

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