-1

For example if:

String str = "100101010";

Then following should happen:

a[0]=1
a[1]=0
a[2]=0
...

It should hold for large strings also (up to 64 characters).

TheWanderer
  • 13,765
  • 5
  • 37
  • 54
  • 2
    Can you narrow down which part of this problem you are struggling with? This looks like a homework question, which the SO community will regularly boo off the stage. – Joe C Jun 25 '17 at 19:26
  • Possible duplicate of [How do I declare and initialize an array in Java?](https://stackoverflow.com/questions/1200621/how-do-i-declare-and-initialize-an-array-in-java) – Alejandro Montilla Jun 26 '17 at 00:59

3 Answers3

1

One hint: find a chart for ASCII. http://www.asciitable.com/index/asciifull.gif The code for "0" is 48 and the code for "1" is 49. You can convert characters to numbers just by subtracting 48 from the ASCII value.

int value = str.charAt(0) - 48;

It's important to realize that a Java char is just an integer type just like int and byte. You can do math with them. With that idea in mind, you should be able figure out the rest yourself.

(This is technically a duplicate since I answered a similar question long ago, but I can't find it, so you get a freebie.)

markspace
  • 9,246
  • 2
  • 20
  • 35
1
 public static int[] getAsArray(String value){
        // not null ;  not empty ;  contains only 0 and 1    
        if(value == null || value.trim().length()<1 || !value.matches("[0-1]+")){
            return new int[0];
        }
        //if it necessary !value.matches("[0-1]+" regex to validate 
        value = value.trim();
        value = value.length()>64 ? value.substring(0,63) : value;// up to 64 characters
        int[] valueAsInt = new int[value.trim().length()];
        for (int i = 0 ;i<value.length();i++){
            valueAsInt[i]=(int)value.toCharArray()[i]-48;
        }
        return valueAsInt;
    }

also if it's possible use shor or byte type as it's enoght to store 0,1 and you consume less memory as with int

xyz
  • 4,512
  • 2
  • 20
  • 32
-2

I don't know why you want to do this, but it is a simple problem.

 public static void main (String[] args) {

        String s = "111232";
        String element[] = s.split("");
        System.out.println(element[0]);
        System.out.println(element[1]);
        System.out.println(element[2]);
        System.out.println(element[3]);
        System.out.println(element[4]);
        System.out.println(element[5]);

    }
lambad
  • 910
  • 8
  • 20