LastIndexOf()
方法返回指定字符或字符串在给定字符串中最后一次出现的位置索引。
示例
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
// returns last index of 'c'
int index = str.LastIndexOf('c');
Console.WriteLine(index);
Console.ReadLine();
}
}
}
// Output: 3
LastIndexOf() 语法
字符串 LastIndexOf()
方法的语法是:
LastIndexOf(String value, int startIndex, int count, StringComparison comparisonType)
在此,LastIndexOf()
是 String
类的一个方法。
LastIndexOf() 参数
LastIndexOf()
方法接受以下参数:
- value - 要搜索的子字符串
- startIndex - 搜索的起始位置。搜索从 startIndex 向给定
string
的开头进行。 - count - 要检查的字符数。
- comparisonType - 枚举值,指定搜索规则
LastIndexOf() 返回值
- 返回指定字符/字符串最后一次出现的位置索引
- 如果找不到指定的字符/字符串,则返回 -1。
示例 1:带 startIndex 的 C# 字符串 LastIndexOf()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
// returns last index of 'c'
int index = str.LastIndexOf('c', 2);
Console.WriteLine(index);
Console.ReadLine();
}
}
}
输出
1
注意这行:
int index = str.LastIndexOf('c', 2);
这里,
c
- 要搜索的char
2
- 搜索的起始索引(搜索从索引 2 向 str 的开头进行)
示例 2:带 startIndex 和 count 的 C# 字符串 LastIndexOf()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
int startIndex = 5;
int count = 2;
// returns -1 as 'c' is not found
int index = str.LastIndexOf('c', startIndex, count);
Console.WriteLine(index);
Console.ReadLine();
}
}
}
输出
-1
这里,
int index = str.LastIndexOf('c', startIndex, count);
从 str 字符串索引 5 向开头搜索 2 个字符('e'
和 'r'
)。
示例 3:带 StringComparison 的 C# 字符串 LastIndexOf()
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;
// ignores letter case
int index1 = str.LastIndexOf("CE", startIndex, count, comparisonType1);
Console.WriteLine(index1);
// considers letter case
int index2 = str.LastIndexOf("CE", startIndex, count, comparisonType2);
Console.WriteLine(index2);
Console.ReadLine();
}
}
}
输出
1 -1
这里,
comparisonType1
- 忽略字母大小写comparisonType2
- 考虑字母大小写