0

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!

1
  • You do something like this to get a string from the chars, the rest you can probably figure out already :) String s = "" + binaryString[j] + binaryString[j + 1]; Commented Feb 24, 2014 at 1:04

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.