温馨提示×

c# lastindexof 怎样返回-1的情况

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

在C#中,IndexOf方法用于查找一个字符串在另一个字符串中首次出现的位置。如果没有找到该字符串,则返回-1。以下是一个简单的示例:

using System;

class Program
{
    static void Main()
    {
        string original = "Hello, I am a programming assistant.";
        string searchString = "programming";

        int index = original.IndexOf(searchString);

        if (index != -1)
        {
            Console.WriteLine($"The index of '{searchString}' is: {index}");
        }
        else
        {
            Console.WriteLine($"The string '{searchString}' was not found in the original string.");
        }
    }
}

在这个示例中,我们查找searchString(“programming”)在original字符串中的位置。IndexOf方法返回该字符串在original中首次出现的位置,即8。如果searchString不在original中,IndexOf方法将返回-1。

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

推荐阅读:c# lastindexof 能处理Unicode吗

0