温馨提示×

c# lastindexof 如何指定搜索范围

c#
小樊
85
2024-11-24 00:00:34
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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"),如果找到了,就输出它的位置,否则输出未找到的消息。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c#中lastindexof的作用是什么

0