温馨提示×

c# lastindexof 如何指定搜索范围

c#
小樊
105
2024-11-24 00:00:34
栏目: 编程语言

在C#中,IndexOf方法用于查找一个字符串在另一个字符串中首次出现的位置。如果你想指定搜索范围,可以使用IndexOf方法的第二个参数,即startIndexstartIndex参数表示从指定索引处开始搜索子字符串。这里有一个例子:

using System; class Program { static void Main() { string original = "Hello, I am a programming assistant."; string searchString = "programming"; // 查找 searchString 在 original 中的位置,从索引 7 开始搜索 int index = original.IndexOf(searchString, 7); if (index != -1) { Console.WriteLine($"The index of '{searchString}' is: {index}"); } else { Console.WriteLine($"The string '{searchString}' was not found."); } } } 

在这个例子中,我们从索引7开始搜索searchString(即"programming"),如果找到了,就输出它的位置,否则输出未找到的消息。

0