简体   繁体   English

将 int 数组转换为 char 数组

[英]Converting int array to char array

Is it possible to cast an int array to a char array ?是否有可能cast一个int arraychar array If so - how ?如果是这样 - how


I'm currently working on a project where I need to create an char array containing the alphabet .我目前正在做一个项目,我需要create an char array包含alphabet create an char array My current code creats an int array (which should be converted to an char array - in one Line! ):当前的code了一个int array (它应该converted为一个char array -在一行中! ):

return IntStream.range('a', 'z' + 1).toArray();

Yeah, we're missing a stream method to produce a char array.是的,我们缺少生成字符数组的流方法。 Maybe a whole CharStream class.也许是整个 CharStream 类。 In any case, no, you cannot cast between int[] and char[] .无论如何,不​​,您不能在int[]char[]

In the meantime, it's getting a long line, but it works:与此同时,它排起了长队,但它有效:

    return IntStream.rangeClosed('a', 'z')
            .mapToObj(c -> Character.toString((char) c))
            .collect(Collectors.joining())
            .toCharArray();

This gives a char[] containing这给出了一个char[]包含

[a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z]

From Java-11 and onwards , you can use .mapToObj(Character::toString) instead of .mapToObj(c -> Character.toString((char) c)) , so your overall code boils down to :Java-11开始,您可以使用.mapToObj(Character::toString)而不是.mapToObj(c -> Character.toString((char) c)) ,因此您的整体代码归结为:

return IntStream.rangeClosed('a', 'z')
        .mapToObj(Character::toString)
        .collect(Collectors.joining())
        .toCharArray();

Let's keep it one line then:然后让我们保持一行:

return IntStream.range('a', 'z' + 1).mapToObj(i -> Character.valueOf((char) i)).toArray(Character[]::new);

This converts from IntStream , to Stream<Character> .这将从IntStream转换为Stream<Character> Keep in mind chars and ints are essentially the same in terms of many calculations, so this step may be unnecessary (especially for comparisons).请记住,就许多计算而言,chars 和 ints 本质上是相同的,因此这一步可能是不必要的(特别是对于比较而言)。

Edit:编辑:

Fixed the above line to be functional, there is a better solution but I'm still trying to find it again.修复了上面的行以使其正常工作,有一个更好的解决方案,但我仍在尝试再次找到它。 It currently returns a Character[] array.它当前返回一个Character[]数组。

Without the 1 line restriction it's simple to just remake the array, treating a as your 0 index.如果没有 1 行限制,只需重新制作数组,将a视为您的 0 索引就很简单。

char[] back = new char[('z' + 1) - 'a'];
IntStream.range('a', 'z' + 1).forEach(i -> back[i - 'a'] = (char) i);
return back;

You cannot cast int array to char array because there are absolutely different types.您不能将 int 数组转换为 char 数组,因为有绝对不同的类型。

There are 2 possible options:有两种可能的选择:

1) create a char array and copy each value from int array 2) use generic lists or collections. 1) 创建一个 char 数组并从 int 数组中复制每个值 2) 使用通用列表或集合。 You can simple use it for casting您可以简单地将它用于铸造

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

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