summerNight
summerNight

Reputation: 1496

Array at index 0 is empty

String A = "00000000"; //8-bit
String [] Aarr = A.split("");
String [] Aarr1= Aarr.clone();
//trying to do a arithmetic right shift here
Aarr[0]=Aarr1[0];
Aarr[1]=Aarr1[0];
Aarr[2]=Aarr1[1];
Aarr[3]=Aarr1[2];
Aarr[4]=Aarr1[3];
Aarr[5]=Aarr1[4];
Aarr[6]=Aarr1[5];
Aarr[7]=Aarr1[6];
System.out.print(Arrays.toString(Aarr));

Why am I getting the output as [,,0,0,0,0,0,0,0] instead of [,0,0,0,0,0,0,0,0] where the first element is empty?

Upvotes: 2

Views: 1321

Answers (3)

Klazen108
Klazen108

Reputation: 690

How about a loop:

char[] shiftResult = new char[8]; //Or whatever type it has to be
shiftResult[0] = A.charAt(0);
shiftResult[1] = A.charAt(0);
for (int i = 2; i < 8; i++) {
    shiftResult[i] = A.charAt(i-1);
}

No empty string splitting required.

Upvotes: 1

Henry Keiter
Henry Keiter

Reputation: 17168

This is happening because when you split a string with the empty string as the delimiter, the first result is always the empty string: because every possible string can be written as "" + "" + "string content". Therefore, the first place to "split" this string using the empty string is right there at the beginning.

Your array, right after you split the string, looks like this:

["", "0", "0", "0", "0", "0", "0", "0", "0"]

Since you're right-shifting your array and copying the first element ("") into both slots 0 and 1, you end up with two empty strings at the beginning in the final output.

["", "", "0", "0", "0", "0", "0", "0", "0"]

Note that the same problem can occur at the end of strings: because all strings end with "" + "" as well. However, in the common use of Java's String.split, trailing empty strings are discarded.

Upvotes: 7

brak2718
brak2718

Reputation: 84

there are 9 elements in your array instead of 8. Is that intentional? Code should work otherwise.

Upvotes: 0

Related Questions