Pick the last item quickly after .Split ()

I have this code:

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

and I would like to save the last element of string[] in stringCutted after splitting, directly, quickly, without saving the divided array in a variable and accessing this element with array[array.length] .

Is this possible in C #?

+47
string arrays split c #
Aug 31 '11 at 12:25
source share
5 answers

If you are using .NET 3.5 or higher, it is easy to use 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 one-dimensional array), so this will not lead to iterating over the entire array to find the last element. On the other hand, this optimization is undocumented ...

+90
Aug 31 '11 at 12:27
source share
β€” -
 stringCutted=myString.Split("/").Last() 

But, just FYI, if you try to get the file name from the path, this works better:

 var fileName=System.IO.Path.GetFileName("C:\\some\path\and\filename.txt"); // yields: filename.txt 
+21
Aug 31 '11 at 12:27
source share

Since you need a solution that returns the last element directly, quickly, without saving the broken array, I think this might be useful:

 stringCutted = myString.Substring(myString.LastIndexOf("/")+1); 
+11
Aug 31 '11 at 12:40
source share

Use LINQ

 "t/e/s/t".Split("/").Last(); 
+3
Aug 31 '11 at 12:31
source share

To use this code, I skip the last element from the Url link.

 string url = Request.Url.ToString().Substring(0, Request.Url.ToString().LastIndexOf('/')); 
+1
Dec 01 '15 at 16:33
source share



All Articles