Java – use the for loop to move an array of characters

I created a char []

[A,A,B,C]

I want to delete the last character, then move the other characters up one and store a new character at the first index So it looks like this:

[D,B]

How do I use one or two for loops to do this I have the right idea, I just don't realize it correctly

char[] array = new char[4]; //Array looks like [A,C]

for(int i = 0; i <= array.length - 2; i++) {
    array[i] = array[i + 1];
}
array[0] = 'D'; //This should be the new char at index 0.

Solution

Iterating from the end to the beginning of the array makes more sense:

char[] array = new char[4]; //Array looks like [A,C]

for(int i = array.length - 1; i > 0; i--) {
    array[i] = array[i - 1];
}
array[0] = 'D';
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>