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#?
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 .
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)".
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.
Yes, . split() always preserves the order of the characters in the string.
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...
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With