1、indexOf()spa
indexOf("\\"):返回"\\"字符在此實例中第一個出現的索引位置,實例的下標是從0開始,若是未找到則返回-1.code
indexOf("\\", 7):返回在此實例中從下標7開始的,第一次出現"\\"的位置,若是未找到返回-1.blog
2、lastIndexOf()
索引
lastIndexOf("\\"):返回"\\"在此實例中最後一個出現的索引位置。即從右向左搜索,第一次出現的"\\"的位置,若是未找到則返回-1.字符串
lastIndexOf("\\", 7):返回在此實例中從下標0開始到下標7結束的這一段子串中,最後一次出現"\\"的位置 。即從右向左搜索,第一次出現的"/"的位置,若是未找到則返回-1.string
3、subString()it
Substring:截取字符串。Substring(7,2)表示從下標7開始,截取長度爲2的字符串,Substring(7)表示從下標7開始,一直截取到字符串末尾。io
PS:indexOf和lastIndexOf的區別就搜索的方向不同,indexOf是從左向右,lastIndexOf是從右向左,儘管搜索方向不同,可是字符下標依然從左向右加1,從0開始。ast
4、例子:class
代碼:
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(); } } }
運行結果: