I have a char array called data.
I should write a method that makes it possible to return the array but with a starting point that is an integer variable called beginIndex.
Example: array contains 'A', 'B', 'C', 'D' and beginIndex = 2. Then it should return 'B', 'C', 'D' (yes the index himself in this case the 2nd letter should be included as well!)
How do I do this? Or is it wiser to change it into a String and later change it back into a char array?
You can use the method Arrays.copyOfRange (Link to the Java 11 Documentation for this method)
Parameters of this method are:
An example how to use it:
char[] originalArray = {'a', 'b', 'c', 'd'};
char[] secondArray = Arrays.copyOfRange(originalArray, 1, test.length);
In this example secondArray contains only 'b', 'c' and 'd'.
A method for your needs, where the the input equals the index-1 could look like this:
public static char[] arrayFromPosition(char[] array, int position) {
return Arrays.copyOfRange(array, position-1, array.length);
}
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