Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select last element quickly after a .Split()

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#?

like image 617
markzzz Avatar asked Aug 31 '11 12:08

markzzz


People also ask

How do you get the last part of a split in Python?

Use the str. rsplit() method with maxsplit set to 1 to split a string and get the last element. The rsplit() method splits from the right and will only perform a single split when maxsplit is set to 1 .

How do you find the last part of a string?

By call charAt() Method If we want to get the last character of the String in Java, we can perform the following operation by calling the "String. chatAt(length-1)" method of the String class. For example, if we have a string as str="CsharpCorner", then we will get the last character of the string by "str. charAt(11)".

Which is faster split or substring?

When you run this multiple times, the substring wins on time hands down: 1,000,000 iterations of split take 3.36s, while 1,000,000 iterations of substring take only 0.05s.

Does string split preserve order?

Yes, . split() always preserves the order of the characters in the string.


2 Answers

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

like image 151
Jon Skeet Avatar answered Sep 20 '22 07:09

Jon Skeet


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 
like image 24
Jamiec Avatar answered Sep 18 '22 07:09

Jamiec