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();
        }
    }
}

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM