在.Split()之后快速选择最后一个元素

我有这个密码:

stringCutted = myString.Split("/"). // ???

我想在 stringCutted中直接快速地存储拆分后 string[]的最后一个元素,而不需要将拆分后的数组存储在变量中并使用 array[array.length]访问该元素。

这在 C # 中可行吗?

120514 次浏览
stringCutted=myString.Split("/").Last()

But, just FYI, if you're trying to get a filename from a path, this works heaps better:

var fileName=System.IO.Path.GetFileName("C:\\some\path\and\filename.txt");
// yields: filename.txt

If you're using .NET 3.5 or higher, it's easy using LINQ to Objects:

stringCutted = myString.Split('/').Last();

Note that Last() (without a predicate) is optimized for the case where the source implements IList<T> (as a single-dimensional array does) so this won't iterate over the whole array to find the last element. On the other hand, that optimization is undocumented...

Use LINQ

"t/e/s/t".Split("/").Last();

Since you want a solution that returns the last element directly, quickly, without store the splitted array, i think this may be useful:

stringCutted = myString.Substring(myString.LastIndexOf("/")+1);

For using this code, I skip last element from the Url link.

string url = Request.Url.ToString().Substring(0, Request.Url.ToString().LastIndexOf('/'));

For Addition:

When string format like 'a/b/c/d' then

yourstring.Split("/").Last();

When string format like \head_display\27_[Item A]\head_image\original_image\1_Item A.png

yourstring.Split("\\").Last();

first '\' actually to skip second '\'