Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

start a char array from a certain index

Tags:

java

arrays

char

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?

like image 284
Ciro Mertens Avatar asked Nov 27 '25 12:11

Ciro Mertens


1 Answers

You can use the method Arrays.copyOfRange (Link to the Java 11 Documentation for this method)

Parameters of this method are:

  1. The original array
  2. the index to start from, inclusive
  3. the final index of the range, exclusive

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);
}
like image 98
csalmhof Avatar answered Nov 29 '25 00:11

csalmhof



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!