Skip to content
Advertisement

start a char array from a certain index

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?

Advertisement

Answer

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]
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement