33

What is the best way to convert an integer into a character array?

Input: 1234

Output: {1,2,3,4}

Keeping in mind the vastness of Java language what will be the best and most efficient way of doing it?

2
  • 1
    I am looking for an efficient way. I can think of getting each digit out by %10, converting it to char and adding to an array. And at last reverse the array. Any better method?? Commented Aug 30, 2012 at 8:29
  • 1
    stackoverflow.com/a/19237615/912319 Commented Aug 16, 2019 at 10:13

7 Answers 7

67
int i = 1234;
char[] chars = ("" + i).toCharArray();
Sign up to request clarification or add additional context in comments.

1 Comment

Hey would you be able to explain how (""+i) part of that solution works are you just saying empty string + int = a string of that int.
54

You could try something like:

String.valueOf(1234).toCharArray();

Comments

16

Try this...

int value = 1234;
char [] chars = String.valueOf(value).toCharArray();

Comments

8

You can convert that integer to string and then convert that string to char arary:-

int i = 1234;
String s = Integer.toString(i);
Char ch[] = s.toCharArray();

/*ch[0]=1,ch[1]=2,ch[2]=3,ch[3]=4*/

Comments

2

This will convert an int to a 2 char array. If you are trying to get the minimum amount of chars, try this.

//convert int to char array

int valIn = 111112222;

ByteBuffer bb1 = ByteBuffer.allocate(4);
bb1.putInt(valIn); 

char [] charArr = new char[4];
charArr[0] = bb1.getChar(0);
charArr[1] = bb1.getChar(2);

//convert char array to int

ByteBuffer bb2 = ByteBuffer.allocate(8);
bb2.putChar(0,charArr[0]);
bb2.putChar(2,charArr[1]);

long valOut = bb2.getInt(0);

Comments

1

I was asked this question in google interview. If asked in interviews use module and division. Here is the answer

List<Integer> digits = new ArrayList<>();
//main logic using devide and module
for (; num != 0; num /= 10)
    digits.add(num % 10);

//declare an array
int[] arr = new int[digits.size()];
//fill in the array
for(int i = 0; i < digits.size(); i++) {
    arr[i] = digits.get(i);
}
//reverse it.
ArrayUtils.reverse(arr);

Comments

-2

Say that you have an array of ints and another method that converts those ints to letters, like for a program changing number grades to letter grades, you would do...

public char[] allGradesToLetters()
   {
      char[] array = new char[grades.length];

      for(int i = 0; i < grades.length; i++)
      {
         array[i] = getLetter(grades[i]);
      }

      return array;
   }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.