I know that this works to get the first item of an array
string aString = @"hello/all\this\is/a\test";
string firstItemOfSplit = aString.Split(new char[] {'\\', '/'})[0];
//firstItemOfSplit = hello
is there a way to get the last item? Something like
string aString = @"hello/all\this\is/a\test";
string lastItemOfSplit = aString.Split(new char[] {'\\', '/'})[index.last];
//lastItemOfSplit = test
您可以使用 System.Linq 中的 IEnumerable.Last() 扩展方法。
string lastItemOfSplit = aString.Split(new char[] {@"\"[0], "/"[0]}).Last();
Like by using the IEnumerable.Last() extension method? Include System.Linq
and you'll have it.
You could always use LINQ:
string lastItem = aString.Split(...).Last();
Note that Enumerable.Last()
is optimized when working on an IList<T>
and you're not applying a predicate - so it's not even going to walk over the sequence to find the last one. (Not that it's likely to be an issue anyway.)
If you can use Linq:
string aString = @"hello/all\this\is/a\test";
string lastItemOfSplit = aString.Split("\/".ToCharArray ()).Last();
Here is a more GC-friendly version that doesn't require linq.
string aString = @"hello/all\this\is/a\test";
string lastItemOfSplit =
aString.Substring(aString.LastIndexOfAny(@"\/".ToCharArray ()) + 1);
使用 .NET Core 3.0(和 .NET Standard 2.1)(C# 8),您可以使用索引类型( Documentation
):
string lastValue = aString.Split(new char[] { '\\', '/' })[^1];
this one i tried and it worked.
string LastItem= (@"hello/all\this\is/a\test").Split(new char[] {@"\"[0], "/"[0]}).Last();
Console.WriteLine(LastItem);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.