3

I'm trying to convert a integer number to an array of chars without using String operations.

My attempt was:

int number = 12;
char[] test = Character.toChars(number);

for (char c : test)
    System.out.println(c);

There is no output, and should give me:

'1'

'2'

How can I fix this? Thank you!

5
  • Go through the implementation of Integer.toString() and the related methods. Commented Oct 8, 2013 at 1:27
  • Why the restriction on String operations? In my long career, nobody has ever placed such a restriction on me. Commented Oct 8, 2013 at 1:33
  • You're mistaken about what Character.toChars() method actually does. It "Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array." Its int parameter specifies "a Unicode code point" Commented Oct 8, 2013 at 1:36
  • @DavidWallace - Probably homework. Commented Oct 8, 2013 at 1:38
  • Ahh! Teacher preparing them for the real world, where this never happens. Say no more. Commented Oct 8, 2013 at 2:05

4 Answers 4

4

Try something like this:

int number = 12345;

char[] arr = new char[(int) (Math.log10(number) + 1)];

for (int i = arr.length - 1; i >= 0; i--) {
    arr[i] = (char) ('0' + (number % 10));
    number /= 10;
}

System.out.println(Arrays.toString(arr));
[1, 2, 3, 4, 5]

Note that floor(log10(n) + 1) returns the number of digits in n. Also, if you want to preserve your original number, create a copy and use that in the for-loop instead.

Also note that you might have to adapt the code above if you plan on also handling non-positive integers. The overall idea, however, should remain the same.

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

6 Comments

Yes, but log10 works with doubles, and could therefore be subject to rounding errors in some implementations. This implies that there is a risk that the array won't be long enough to store all the characters in some cases. So this answer is not as good as an answer that just works with integers, strings and characters (like the other three answers here).
@DavidWallace The implementation should be that defined by the docs. As for rounding errors, please provide an example of such a case (i.e. a positive number for which this does not work).
I think it's safe to assume that the OP will be using the standard java.lang.Math.
The docs for java.lang.Math say that the result will be within 1 ULP of the right answer. That's not good enough.
@DavidWallace Ok, so do you have an example for which this does not work? I myself am eager to see one.
|
1

char[] test = Integer.toString(number).toCharArray();

2 Comments

without using String operations
I'm leaving this here, because a future SO user may come across this question, while searching for a way to do this same thing, but without the bizarre restriction. In their case, this is a useful answer, although I freely admit that it doesn't meet the OP's immediate needs.
0

Extract each digit of the number, convert it into a character(by adding '0') and store them into a char array. Let us know what you have tried.

5 Comments

I don't think there's a guarantee that '0' is encoded as 48, '1' as 49, and so on. Depending on that behavior is bad practice.
@bdares A char is a UTF-16 code unit. That cannot change.
I believe there IS such a guarantee - Java defines what encoding is used for its characters. But for readability, it would be better to add '0' (the character), rather than 48.
Absolutely, I have never heard java char deviates from ASCII
Even if that may always be technically correct, it's still not a clean solution.
0

+1 for @arshajii's code log10(n) + 1 is something new for me as well. If you intend to use Vectors instead of arrays you can also follow this procedure(But the Vector has elements in reverse order) in which you never need to calculate the size of number itself

public static Vector<Character> convert(int i) {
        Vector<Character> temp = new Vector<Character>();
        while (i > 0) {
            Character tempi = (char) ('0' + i % 10);
            i = i / 10;
            temp.add(tempi);
        }
        return temp;
    }

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.