0

I have a number that is submitted by the user.
I want to make something like this: 1568301
to an array like this: 1, 5, 6, 8, 3, 0, 1.

How can I do this without adding "," between every digit or something like that? (type int).

Thanks.

1
  • When you say (type int), do you mean that you want the array to be of type int? Commented Nov 22, 2012 at 15:42

8 Answers 8

9
String str = "123456";
str.toCharArray();

will do roughly what you want. A more complex version using a regular expression is:

String str = "123456";
str.split("(?<!^)");

which uses a negative lookbehind (split() takes a regexp - the above says split on anything provided the element to the left isn't the start-of-line. split("") would give you a leading blank string).

The second solution is more complex but gives you an array of Strings. Note also that it'll give you a one-element empty array for a blank input. The first solution gives you an array of Chars. Either way you'll have to map these to Integers (perhaps using Integer.parseInt() or Character.digit()?)

Sign up to request clarification or add additional context in comments.

Comments

3

"1568301".toCharArray() should do the job.

Comments

2

You can use the Split with "" It'll be like this:

String test = "123456";
String test2[] = test.split("");
for (int i = 1; i < test2.length; i++) {
    System.out.println(test2[i]);
}

1 Comment

Don't forget to check for an input of "" otherwise this will blow up!
1

If your number is in String format, you can simply do this:

    String str = "1568301";
    char[] digitChars = str.toCharArray();

Comments

1

Are expecting something like this

    String ss ="1568301";
    char[] chars = ss.toCharArray();

Comments

1

cant you simply populate the array by iterating over the String ??

char[] arr = new char[str.length];
for(int i=0; i<str.length; i++){
   arr[i] = str.charAt(i);
}

or even better

char[] arr = "0123456".toCharArray();

Comments

1

To get the values in an array of integers:

String str = "1568301";
int[] vals = new int[str.length];
for (int i = 0; i < str.length(); i++) {
    vals[i] = Character.digit(str.charAt(i), /* base */ 10));
}

The second parameter of Character.digit(char, int) is the number base. I'm assuming your number is base 10.

Comments

1

I guess you are looking at to have an array of int.

I would suggest to have the following code :

String str = "1568301";
int [] arr = new int[str.length()];
for(int i=0; i<arr.length; i++)
{
  arr[i] = str.charAt(i)-'0';
}

3 Comments

why negative, can someone please explain?
I didn't mean to downvote your answer, but the site won't let me change my vote until you've edited your answer. If you add even a single space, I can fix my vote.
Fixed! Sorry for the clumsiness.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.