Is there a substring equivalent for an array?
Input new char[] foo = {'a', 'b', 'c', 'd', 'e', 'f'}
If this was a String abcdef
I would use .Substring(0, 2)
and get ab
Is there a built in method that would give me char[] {'a', 'b'}
if the input indexes were 0, 2
?
Code Example
char[] foo = {'a', 'b', 'c', 'd', 'e', 'f'};
char[] bar = foo.**Method**(0, 2); //what can I do here?
Console.WriteLine(bar);
//Output would be` **ab**
I know I could just convert the Char array back to a String, use Substring and back to a Char Array. But that would take some extra lines of Code and I want to know, if it is possible with only 1 built-in Method.
There isn't a single method for this but you can use Linq to get the same affect like
var newArr = set.Skip(n).Take(k).ToArray();
Further step could be writing an extension method
public static class MyExtensions
{
public static T[] Subsequence<T>(this IEnumerable<T> arr,int startIndex, int length)
{
return arr.Skip(startIndex).Take(length).ToArray();
}
}
and use it as
var newset = new[] { 1, 2, 3, 4, 5 }.Subsequence(1, 2);
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