C# 中indexOf、lastIndexOf、subString方法的理解

一、indexOf()

indexOf("\\"):返回"\\"字符在此实例中第一个出现的索引位置,实例的下标是从0开始,如果未找到则返回-1.

indexOf("\\", 7):返回在此实例中从下标7开始的,第一次出现"\\"的位置,如果未找到返回-1.

二、lastIndexOf()

lastIndexOf("\\"):返回"\\"在此实例中最后一个出现的索引位置。即从右向左搜索,第一次出现的"\\"的位置,如果未找到则返回-1.

lastIndexOf("\\", 7):返回在此实例中从下标0开始到下标7结束的这一段子串中,最后一次出现"\\"的位置 。即从右向左搜索,第一次出现的"/"的位置,如果未找到则返回-1.

三、subString()

Substring:截取字符串。Substring(7,2)表示从下标7开始,截取长度为2的字符串,Substring(7)表示从下标7开始,一直截取到字符串末尾。

 

PS:indexOf和lastIndexOf的区别就搜索的方向不一样,indexOf是从左向右,lastIndexOf是从右向左,尽管搜索方向不一样,但是字符下标依然从左向右加1,从0开始。

四、例子:

代码:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string FilePath = "D:\\files\\small.txt";
            Console.WriteLine(FilePath);

            int a= FilePath.IndexOf("f");
            Console.WriteLine(a);

            int b = FilePath.IndexOf("s",3);
            Console.WriteLine(b);

            int c = FilePath.LastIndexOf("x");
            Console.WriteLine(c);

            int d = FilePath.LastIndexOf("s",15);
            Console.WriteLine(d);

            string e = FilePath.Substring(7,2);
            Console.WriteLine(e);

            string f = FilePath.Substring(7);
            Console.WriteLine(f);

            int index = FilePath.LastIndexOf('\\');
            Console.WriteLine(index);
            string folder = FilePath.Substring(0, index);
            Console.WriteLine(folder);
            string ShapeName = FilePath.Substring(index + 1);
            Console.WriteLine(ShapeName);

            Console.ReadKey();
        }
    }
}
复制代码

运行结果:

 

posted on   Keepshining  阅读(14636)  评论(0编辑  收藏  举报

编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

导航

统计

点击右上角即可分享
微信分享提示