简体   繁体   中英

How do I substring this array?

I have a char array that takes in a binary string of length n. It can only have 0s and 1s.

What I want to do is, I want to make a string array and store the first 2 values of the char array array jointly to the 1st index of this string array.

For example -

11011101

Is my char array. I want to convert it to an array that would be like -

newArray[0] = 11;
newArray[1] = 01;
newArray[2] = 11;
newArray[3] = 01;

So basically I just want to split every 2 integers and save them to the newArray in this manner.

My problem is

for (int j = 0; j < binaryString.length; j++) {
        lookUp[j] = binaryString.toString().substring(j, j+1);
    }

Which is just giving me the memory locations of the indexes.

Thanks in advance!

This is pretty easy to do using String.split .

This code:

char[] cArray = {'1','1','0','1','1','1','0','1'};
String arrayAsString = new String(cArray);
String[] stringArray = arrayAsString.split("(?<=\\G..)");
System.out.println(java.util.Arrays.toString(stringArray));

Prints this:

[11, 01, 11, 01]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM