Java – 从字节数组中修剪尾随空格
我有类似这样的字节数组:
[77, 83, 65, 80, 79, 67, 32, 32, 32, 32, 32, 32, 32]
大致等于
[M , S, A, P, O, C, , , , , , , ] when printed as chars.
现在我想修剪尾随空格,看起来像:
[77, 83, 65, 80, 79, 67]
最简单的方法吗?
编辑 :我不想处理字符串,因为有可能不可打印的字节,我不能丢失这些数据。 它需要是字节数组:(每当我转换为字符串时,像01(SOH)02(STX)等字节丢失。
编辑2 : 只是为了澄清。 如果我将字节数组转换为字符串,我会丢失数据吗? 现在有点困惑。 如果字节是不同的字符集怎么办?
无需转换为字符串:
byte[] input = /* whatever */; int i = input.length; while (i-- > 0 && input[i] == 32) {} byte[] output = new byte[i+1]; System.arraycopy(input, 0, output, 0, i+1);
测试:
-
[77, 83, 65, 80, 79, 67, 32, 32, 32, 32, 32, 32, 32]
→[77, 83, 65, 80, 79, 67]
-
[77, 83, 65, 80, 79, 67]
→[77, 83, 65, 80, 79, 67]
-
[32, 32, 32, 32, 32, 32, 32]
→[]
-
[]
→[]
-
[77, 83, 65, 80, 79, 67, 32, 32, 32, 32, 32, 32, 32, 80]
→[77, 83, 65, 80, 79, 67, 32, 32, 32, 32, 32, 32, 32, 80]
- 将字节更改为字符串
- call
text = text.replaceAll("\\s+$", ""); // remove only the trailing white space
text = text.replaceAll("\\s+$", ""); // remove only the trailing white space
- 将字符串更改为字节
最简单的方法? 不保证效率或性能,但似乎很容易。
byte[] results = new String(yourBytes).trim().getBytes();
String s = new String(arrayWithWhitespace); s = s.trim(); byte[] arrayWithoutWhitespace = s.getBytes();