Select last element quickly after a .Split()

C#ArraysStringSplit

C# Problem Overview


I have this code :

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

and I'd like to store in stringCutted the last element of the string[] after the split, directly, quickly, without storing the splitted array in a variable and access to that element with array[array.length].

Is this possible in C#?

C# Solutions


Solution 1 - C#

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...

Solution 2 - C#

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

Solution 3 - C#

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

Solution 4 - C#

Use LINQ

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

Solution 5 - C#

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

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

Solution 6 - C#

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 '\'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarkzzzView Question on Stackoverflow
Solution 1 - C#Jon SkeetView Answer on Stackoverflow
Solution 2 - C#JamiecView Answer on Stackoverflow
Solution 3 - C#escrubaloView Answer on Stackoverflow
Solution 4 - C#EduardView Answer on Stackoverflow
Solution 5 - C#Thivan MydeenView Answer on Stackoverflow
Solution 6 - C#MajedurView Answer on Stackoverflow