tags:

views:

173

answers:

4

How do we split the value in an array suppose 124 into three different values 1,2,4?
I want this to be done in java.

+3  A: 
String [] splits = string.split("")
bertolami
or String.valueOf(number).split("")
Peter Lawrey
A: 

Well, the String.getChars() function will give you a char[] array with one character per array element.

So you should be able to do:

char[] k = new char[myString.length()]
myString.getChars(0,myString.length(),k,0);

If you need to convert to an array of integers, you can add

int[] i = new int[k.length]
for(int j = 0; j < k.length; j++) i[j] = k[j] - '0';

If you need to convert from an integer first, just use String myString = Integer.toString(myInt)

Chad Okere
Is "i[j] = '0' - k[j]" correct? It should be fixed to i[j] = k[j] - '0'. Isn't it?
sergdev
+3  A: 

Keep dividing by 10 in a loop and take remainder : n % 10;

fastcodejava
+1  A: 

If it's a string, then you can just take the individual characters with getChars().

If it's a number then you just need to loop and use each digit individually. To start from the end you can iteratively get the last digit by number % 10 and remove it with number / 10. If you start with the first digits, then you can get the digit with number / 100, number / 10, etc. and remove it with number % 100, number % 10, etc.

I'm sure you can convert that description into Java code. I'm not convinced that simply posting a bunch of code here actually helps you in the long term.

Joey