java 字符串和字节数组连接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6963784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String and byte array concatenation
提问by dev mz
I have a String that I have to concatenate with an byte array, so I tried this
我有一个必须与字节数组连接的字符串,所以我尝试了这个
String msg = "msg to show";
byte[] msgByte = new byte[msg.length()];
try {
msgByte = msg.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] command = {2,5,1,5}
byte[] c = new byte[msgByte.length + command.length];
System.arraycopy(command, 0, c, 0, command.length);
System.arraycopy(msjByte, 0, c, command.length, msjByte.length);
for(Byte bt:c)
System.out.println(bt+"");
This is the output:
2 5 1 5 109 115 103 32 ...
but the result that I'm looking for is this
2 5 1 5 m s g ...
这是输出:
2 5 1 5 109 115 103 32 ...
但我正在寻找的结果是这个
2 5 1 5 msg ...
I need it in one array cause it's used as a command for a bluetooth printer.
我需要它在一个数组中,因为它被用作蓝牙打印机的命令。
Is there a way, any suggestions?
有没有办法,有什么建议吗?
Thanks in advance! :)
提前致谢!:)
采纳答案by hoipolloi
You can't have a byte array containing '2 5 1 5 m s g'. From the documentation:
您不能拥有包含“2 5 1 5 ms g”的字节数组。从文档:
The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).
字节数据类型是一个 8 位有符号二进制补码整数。它的最小值为 -128,最大值为 127(含)。
I can't envisage a scenario where you would actually want to join un-encoded bytes with a string, but here's a solution that returns a char[]
.
我无法想象您实际上想要将未编码的字节与字符串连接的场景,但这里有一个解决方案,它返回一个char[]
.
public static void main(String[] args) {
final String msg = "msg to show";
final byte[] command = { 2, 5, 1, 5 };
// Prints [2, 5, 1, 5, m, s, g, , t, o, , s, h, o, w]
System.out.println(Arrays.toString(concat(msg, command)));
}
private static char[] concat(final byte[] bytes, final String str) {
final StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(b);
}
sb.append(str);
return sb.toString().toCharArray();
}
回答by fireshadow52
An alternative would be to do this...
另一种选择是这样做......
String msg = "msg to show";
char[] letters = msg.toCharArray();
byte[] command = {2,5,1,5};
String result;
for (String str: command) {
result += str + " ";
}
for (String str: letters) {
result += str + " ";
}
System.out.println(result);