char数组到int数组 [英] char array to int array

查看:131
本文介绍了char数组到int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串转换为整数数组,以便我可以对它们执行数学运算。我在使用以下代码时遇到问题:

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

这给了我一个无法转换的类型错误,必需:int [] found:char
我还尝试了其他一些方法,比如Character.getNumericValue,只是直接分配它,没有任何修改。在这些情况下,它总是输出相同的垃圾[I @ 41ed8741,无论我使用什么转换方法或(!)字符串的实际值是什么。它是否与unicode转换有关?

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?

推荐答案

您的解决方案存在许多问题。第一个是循环条件 i> raw.length()错误 - 你的循环永远不会被执行 - 条件应该是 i< raw.length()

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()

第二个是演员。您正在尝试强制转换为整数数组。实际上,因为结果是char,所以不必转换为int - 转换将自动完成。但转换的数字并不是你想象的那样。它不是您期望的整数值,但实际上是char的ASCII值。因此,您需要减去ASCII值为零以获得您期望的整数值。

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

这篇关于char数组到int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆