C# 字符串 - LastIndexOf() 方法

C# 字符串的 LastIndexOf() 方法用于返回指定字符或字符串在此字符串对象中最后一次出现的索引位置。

需要注意的是,此方法可以通过传递不同的参数进行重载。在下面的示例中,我们可以使用此方法的重载方法 LastIndexOf()

语法

以下是 C# 字符串的语法: LastIndexOf(Char) 方法 -

public int LastIndexOf(char value);

参数

此方法接受一个参数,该参数可以是要搜索的字符或字符串。

返回值

如果找到该字符,此方法将返回一个 32 位有符号整数,表示指定值的索引位置。如果未找到该字符,则返回 -1。

示例 1:使用 LastIndexOf(char value) 语法

以下是使用 LastIndexOf(char value) 方法查找字符串中最后一个字符索引的基本示例 -

    
using System;
class Program {
   static void Main() {
      string str = "tutorialspoint";
      int indx = str.LastIndexOf('t');
      Console.Write("Last Index Value of character 't' is " + indx);
   }
}

输出

以下是输出 -

Last Index Value of character 't' is 13

示例 2:使用 LastIndexOf(string value) 语法

让我们来看另一个 LastIndexOf(string value) 方法的示例。在这里,我们使用另一种语法来查找指定字符串的最后一个索引 -

using System;
class Program {
   static void Main() {
      string str = "tutorialspoint point";
      int last_indx = str.LastIndexOf("point");
      Console.Write("Last Index Value of string 'point' is " + last_indx);
   }
}

输出

以下是输出 -

Last Index Value of string 'point' is 15

示例 3:使用 LastIndexOf(char value, int startIndex) 语法

在此示例中,我们使用 LastIndexOf(char value, int startIndex) 方法从指定索引开始向后搜索,查找字符的最后一次出现位置 -

using System;
class Program {
   static void Main(){
      string text = "Hello, world!";
      int index = text.LastIndexOf('o', 7);
      Console.WriteLine(index);
   }
}

输出

以下是输出 -

4

示例 4:使用 LastIndexOf(char value, int startIndex, int count) 语法

在此示例中,我们使用 LastIndexOf(char value, int startIndex, int count) 方法在指定的字符范围内查找某个字符的最后一次出现位置 -

using System; 
class Program {
   static void Main(){
      string text = "Hii tutorialspoint";
      int index = text.LastIndexOf('i', 12, 6);
      Console.WriteLine("Last occurrence of 'i' is " + index);
   }
}

输出

以下是输出 -

Last occurrence of 'i' is 9

csharp_strings.html