简体   繁体   English

char数组转int数组

[英]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.这给了我一个“不可转换类型”错误,需要:int [] found:char 我还尝试了其他一些方法,如 Character.getNumericValue 并直接分配它,没有任何修改。 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?在那些情况下,它总是输出相同的垃圾“[I@41ed8741”,无论我使用什么转换方法或 (.) 字符串的实际值是什么? Does it have something to do with unicode conversion?跟unicode转换有关系吗?

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()第一个是循环条件i > raw.length()是错误的——你的循环永远不会被执行——条件应该是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.事实上,由于结果是一个字符,您不必强制转换为 int - 转换将自动完成。 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.它不是您期望的整数值,但实际上是字符的 ASCII 值。 So you need to subtract the ASCII value of zero to get the integer value you're expecting.所以你需要减去零的 ASCII 值来得到你期望的整数值。

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

Two ways in Java 8: 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.第二种解决方案可能效率很低,因为它使用正则表达式并为每个数字创建字符串实例。

Everyone have correctly identified the invalid cast in your code.每个人都正确识别了代码中的无效转换。 You do not need that cast at all: Java will convert char to int implicitly:您根本不需要那个转换:Java 会隐式地将char转换为int

String raw = "1233983543587325318";

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

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

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

You shouldn't be casting each element to an integer array int[] but to an integer int :您不应该将每个元素转换为整数数组int[]而是转换为整数int

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

System.out.println(num);

this line:这一行:

num[i] = (int[])list[i];

should be:应该:

num[i] = (int)list[i];

You can't cast list[i] to int[] , but to int .您不能将list[i]int[] ,而是转换为int Each index of the array is just an int, not an array of ints.数组的每个索引只是一个整数,而不是整数数组。

So it should be just所以应该只是

num[i] = (int)list[i];

For future references.供以后参考。 char to int conversion is not implicitly, even with cast.即使使用强制转换,char 到 int 的转换也不是隐式的。 You have to do something like that:你必须做这样的事情:

    String raw = "1233983543587325318";

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

    for (int i = 0; i < list.length; i++){
        num[i] = list[i] - '0';
    }
    System.out.println(Arrays.toString(num));

This class here:http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html should hep you out.这个类在这里:http ://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html应该让你失望。 It can parse the integers from a string.它可以解析字符串中的整数。 It would be a bit easier than using arrays.这比使用数组要容易一些。

Everyone is right about the conversion problem.关于转换问题,每个人都是对的。 It looks like you actually tried a correct version but the output was garbeled.看起来您实际上尝试了正确的版本,但输出是乱码。 This is because system.out.println(num) doesn't do what you want it to in this case:) Use system.out.println(java.util.Arrays.toString(num)) instead, and see this thread for more details.这是因为在这种情况下system.out.println(num)不会做你想要它做的事情:) 使用system.out.println(java.util.Arrays.toString(num))代替,并查看此线程更多细节。

String raw = "1233983543587325318";
char[] c = raw.toCharArray();
int[] a = new int[raw.length()];

for (int i = 0; i < raw.length(); i++) {
   a[i] = (int)c[i] - 48;
} 

You can try like this,你可以这样试试

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] = Integer.parseInt(String.valueOf(list[i]));
}

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

Simple and modern solution简单而现代的解决方案

int[] result = new int[raw.length()]; 
Arrays.setAll(result, i -> Character.getNumericValue(raw.charAt(i))); 

Line num[i] = (int[])list[i];num[i] = (int[])list[i];

It should be num[i] = (int) list[i];应该是num[i] = (int) list[i]; You are looping through the array so you are casting each individual item in the array.您正在遍历数组,因此您正在投射数组中的每个单独的项目。

The reason you got "garbage" is you were printing the int values in the num[] array.你得到“垃圾”的原因是你在 num[] 数组中打印 int 值。 char values are not a direct match for int values. char 值不直接匹配 int 值。 char values in java use UTF-16 Unicode. For example the "3" char translates to 51 int java 中的字符值使用 UTF-16 Unicode。例如,“3”字符转换为 51 int

To print out the final int[] back to char use this loop要将最终的 int[] 打印回 char 使用此循环

for(int i:num)
        System.out.print((char) i);

I don't see anyone else mentioning the obvious:我没有看到其他人提到显而易见的:

We can skip the char array and go directly from String to int array.我们可以跳过char数组和go直接从String到int数组。 Since java 8 we have CharSequence.chars which will return an IntStream so to get an int array, of the char to int values, from a string.由于 java 8 我们有CharSequence.chars它将返回一个IntStream以便从字符串中获取一个 int 数组,从 char 到 int 值。

String raw = "1233983543587325318";
int[] num = raw.chars().toArray();
// num ==> int[19] { 49, 50, 51, 51, 57, 56, 51, 53, 52, 51, 53, 56, 55, 51, 50, 53, 51, 49, 56 }

There are also some math reduce functions on Intstream like sum , average , etc. if this is your end goal then we can skip the int array too. Intstream上还有一些数学归约函数,例如sumaverage等。如果这是您的最终目标,那么我们也可以跳过 int 数组。

String raw = "1233983543587325318";
int sum = raw.chars().sum();
// sum ==> 995

nJoy!开心!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM