【问题标题】:How to get byte values of two concatenated strings...?如何获取两个连接字符串的字节值......?
【发布时间】:2017-04-27 04:54:45
【问题描述】:

程序的输出是:

[B@171ccb0[B@35378d
[B@1d23632

需要的输出是:

[B@171ccb0[B@35378d
[B@171ccb0[B@35378d

请帮忙...

import java.util.Scanner;
import java.io.InputStreamReader;

public class testme {
    public static void main(String[] args) {
        Scanner in = new Scanner(new InputStreamReader(System.in));
        String s = "hello";
        String sb = "hi";
        String sc = s.concat(sb);
        byte[] a, b;
        a = s.getBytes();
        b = sb.getBytes();
        byte[] c = new byte[a.length + b.length];
        System.arraycopy(a, 0, c, 0, a.length);
        System.arraycopy(b, 0, c, a.length, b.length);
        System.out.println(a + "" + b + "\n" + c);
    }
}

【问题讨论】:

  • 您的示例中扫描仪的用途是什么?
  • 整个程序的目的是什么?
  • 这毫无意义。如果您只打印出三个数组(准确地说是这些数组的 toStrings),您将永远不会在输出中看到四次“[B”。此外,字符串表示取决于这些数组的 objectId,这不是确定性的。您可能想要打印数组内容而不是 toString ....
  • @MartinFrank 抱歉,请忽略扫描仪
  • @Kayaman 目的是获取连接字符串的字节值与连接前的值相同

标签: java arrays append concat


【解决方案1】:

在你的结果中

[B@171ccb0, the [B means byte[] and 171ccb0 is the memory address of a variable used, separated by an @.

Similarly, in [B@35378d , 35378d is the memory address of b variable created, and

in [B@1d23632, 1d23632 is the memory address of c variable created.

如果您想知道值是连接的还是不尝试打印 Arrays.toString 方法,

import java.util.Arrays;

public class Solution {
    public static void main(String[] args) {
        String s = "hello";
        String sb = "hi";
        byte[] a, b;
        a = s.getBytes();
        b = sb.getBytes();

        byte[] c = new byte[a.length + b.length];
        System.arraycopy(a, 0, c, 0, a.length);
        System.arraycopy(b, 0, c, a.length, b.length);

        System.out.println(" Arrays.toString(a)= "+Arrays.toString(a));
        System.out.println(" Arrays.toString(b)= "+Arrays.toString(b));
        System.out.println(" Arrays.toString(c)= "+Arrays.toString(c));

    }
}

输出是:

Arrays.toString(a)= [104, 101, 108, 108, 111] 
Arrays.toString(b)= [104, 105] 
Arrays.toString(c)= [104, 101, 108, 108, 111, 104, 105]

参考:How to convert Java String into byte[]?

【讨论】:

    猜你喜欢
    • 2011-11-04
    • 2022-11-16
    • 2022-06-29
    • 2022-12-13
    • 2013-07-10
    • 2014-08-27
    • 2013-11-05
    相关资源
    最近更新 更多