Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

java - char array to int array

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...