char array to int array

daedalus :

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?

auser :

There are a number of issues with your solution. The first is the loop condition i > raw.length() is wrong - your loops is never executed - thecondition should be i < raw.length()

The second is the cast. You're attempting to cast to an integer array. In fact since the result is a char you don't have to cast to an int - a conversion will be done automatically. But the converted number isn't what you think it is. It's not the integer value you expect it to be but is in fact the ASCII value of the char. So you need to subtract the ASCII value of zero to get the integer value you're expecting.

The third is how you're trying to print the resultant integer array. You need to loop through each element of the array and print it out.

    String raw = "1233983543587325318";

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

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

    for (int i : num) {
        System.out.println(i);
    }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related