Java - 从字节数组中修剪尾随空格

时间:2011-10-05 23:02:29

标签: 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 只是为了澄清。如果我将字节数组转换为字符串,我会丢失数据吗?现在有点困惑。如果字节是不同的字符集怎么办?

5 个答案:

答案 0 :(得分:17)

不转换为字符串:

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

试验:

答案 1 :(得分:0)

  • 将字节更改为字符串
  • 致电text = text.replaceAll("\\s+$", ""); // remove only the trailing white space
  • 将字符串更改为字节

答案 2 :(得分:0)

最简单的方法?不保证效率或性能,但似乎很容易。

byte[] results = new String(yourBytes).trim().getBytes();

答案 3 :(得分:0)

trim()的修改字符串byte[]。它不仅剪切了数组的尾部,而且剪切了头部。

public byte[] trimArray(byte[] source) {
    int len = source.length;
    int st = 0;
    byte[] val = source;

    while ((st < len) && (val[st] <= SPACE)) {
        st++;
    }
    while ((st < len) && (val[len - 1] <= SPACE)) {
        len--;
    }
    byte[] result;
    if ((st > 0) || (len < source.length)) {
        result = new byte[len - st];
        System.arraycopy(source, st, result, 0, result.length);
    } else {
        result = source;
    }

    return result;
}

答案 4 :(得分:-1)

String s = new String(arrayWithWhitespace);
s = s.trim();
byte[] arrayWithoutWhitespace = s.getBytes();
相关问题