start a char array from a certain index

Viewed 414

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?

3 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);
}

I created a method for this. This is what it looks like:

public static char[] charIndex(char[] chars, int beginIndex) {
    beginIndex--;
    char[] result = new char[chars.length - beginIndex];
    for(int i = 0; i < chars.length; i++) {
        if(!(i < beginIndex)) result[i - beginIndex] = chars[i];
    }
    return result;
}

Here's how you use it:

char[] chars = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
System.out.println(Arrays.toString(chars));
chars = charIndex(chars, 2);
System.out.println(Arrays.toString(chars));

The output will be:

[a, b, c, d, e, f, g]
[b, c, d, e, f, g]

You can use the below function, its based on 0-index

    public Character[] stripCharArrFromIndex(Character[] arr,int index){
        int arrSize = arr.length;
        Character[] strippedArr = new Character[arrSize - index];
        
        int j=0;
        for(int i=index;i<arrSize;i++){
            strippedArr[j]=arr[i];
            j++;
        }
        return strippedArr;
         
     }

Related