跳到主要内容

C# String LastIndexOf() 字符串最后索引查找方法

LastIndexOf() 方法返回指定字符或字符串在给定字符串内的最后一次出现的索引位置。

示例

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str = "Icecream";

// 返回 'c' 的最后一次出现的索引位置
int index = str.LastIndexOf('c');

Console.WriteLine(index);

Console.ReadLine();
}
}
}

// 输出: 3

LastIndexOf() 语法

字符串 LastIndexOf() 方法的语法如下:

LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType)

在这里,LastIndexOf()String 类的一个方法。

LastIndexOf() 参数

LastIndexOf() 方法接受以下参数:

  • value - 要查找的子字符串
  • startIndex - 搜索的起始位置。搜索从 startIndex 开始,向给定的字符串的开头方向进行。
  • count - 要检查的字符位置数。
  • comparisonType - 枚举值,指定搜索的规则。

LastIndexOf() 返回值

  • 返回指定字符/字符串的最后一次出现的索引
  • 如果未找到指定字符/字符串,则返回**-1**。

示例 1: C# String LastIndexOf() 带有 startIndex

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str = "Icecream";

// 返回 'c' 的最后一次出现的索引位置
int index = str.LastIndexOf('c', 2);

Console.WriteLine(index);

Console.ReadLine();
}
}
}

输出

1

请注意以下行:

int index = str.LastIndexOf('c', 2);

在这里,

  • c - 要查找的字符
  • 2 - 搜索的起始位置(搜索从索引 2 开始,向 str 的开头方向进行)。

示例 2: C# String LastIndexOf() 带有 startIndex 和 count

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str = "Icecream";

int startIndex = 5;
int count = 2;

// 返回 -1,因为 'c' 未找到
int index = str.LastIndexOf('c', startIndex, count);

Console.WriteLine(index);

Console.ReadLine();
}
}
}

输出

-1

在这里,

int index = str.LastIndexOf('c', startIndex, count);

从索引 5 开始搜索 2 个字符('e''r')向 str 的开头方向进行搜索。

示例 3: C# String LastIndexOf() 带有 StringComparison

using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {

string str = "icecream";

int startIndex = 2;
int count = 3;

StringComparison comparisonType1 = StringComparison.CurrentCultureIgnoreCase;
StringComparison comparisonType2 = StringComparison.CurrentCulture;

// 忽略大小写
int index1 = str.LastIndexOf("CE", startIndex, count, comparisonType1);
Console.WriteLine(index1);

// 区分大小写
int index2 = str.LastIndexOf("CE", startIndex, count, comparisonType2);
Console.WriteLine(index2);

Console.ReadLine();
}
}
}

输出

1
-1

在这里,

  • comparisonType1 - 忽略大小写
  • comparisonType2 - 区分大小写