有没有比使用substring()更简单,更短的方法?我试图减少错误因为在键入LastIndexOf和Length,加上计数器时太容易出错.
string filepath = "c:\folder1\folder2\folder3\file1.jpg";
string file = "";
file = filepath.SubString(
(filepath.LastIndexOf("\\")+1),
(filepath.Length - filepath.LastIndexOf("\\")+1)
);
Run Code Online (Sandbox Code Playgroud)
我想得到这个值"file1.jpg".
谢谢...
是的,使用Path.GetFileName
string filepath = "c:\folder1\folder2\folder3\file1.jpg";
string file = Path.GetFileName(filePath);
Run Code Online (Sandbox Code Playgroud)
基于非路径的记录的另一个选项是使用String.Split函数.
string longString = "The cat jump over the brown fox";
string[] splitString = longString.Split(new char[] {' '}); //Splits the string in to array elements wherever it see a space;
string lastWord = splitString[splitString.Length - 1]; //Could throw a error is the length is less than 1
string lastTwoWords = String.Join(" ", splitString.Skip(splitString.Length - 2)); //Could throw a error if the length is less than 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
773 次 |
| 最近记录: |