Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char array to int array

Tags:

java

I'm trying to convert a string to an array of integers so I could then perform math operations on them. I'm having trouble with the following bit of code:

String raw = "1233983543587325318";

char[] list = new char[raw.length()];
list = raw.toCharArray();
int[] num = new int[raw.length()];

for (int i = 0; i < raw.length(); i++){
    num[i] = (int[])list[i];
}

System.out.println(num);

This is giving me an "inconvertible types" error, required: int[] found: char I have also tried some other ways like Character.getNumericValue and just assigning it directly, without any modification. In those situations, it always outputs the same garbage "[I@41ed8741", no matter what method of conversion I use or (!) what the value of the string actually is. Does it have something to do with unicode conversion?

like image 582
daedalus Avatar asked Jun 04 '12 18:06

daedalus


1 Answers

Two ways in Java 8:

String raw = "1233983543587325318";

final int[] ints1 = raw.chars()
    .map(x -> x - '0')
    .toArray();

System.out.println(Arrays.toString(ints1));

final int[] ints2 = Stream.of(raw.split(""))
    .mapToInt(Integer::parseInt)
    .toArray();

System.out.println(Arrays.toString(ints2));

The second solution is probably quite inefficient as it uses a regular expression and creates string instances for every digit.

like image 151
Martin Avatar answered Oct 23 '22 12:10

Martin