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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7668748/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:55:30  来源:igfitidea点击:

Java - Trimming trailing whitespace from a byte array

java

提问by Dominic Bou-Samra

I have byte arrays similar to this:

我有与此类似的字节数组:

[77, 83, 65, 80, 79, 67, 32, 32, 32, 32, 32, 32, 32]

roughly equal to

大致等于

[M , S, A, P, O, C,  ,  ,  ,  ,  ,  ,  ] when printed as chars.

Now I want to trim the trailing whitespace so it looks like:

现在我想修剪尾随空格,使其看起来像:

[77, 83, 65, 80, 79, 67]

Easiest way to do this?

最简单的方法来做到这一点?

Edit: I don't want to deal with Strings because there is the possibility for non-printable bytes, and I can not afford to lose that data. It needs to be byte arrays :( Whenever I do convert to Strings, bytes like 01 (SOH) 02 (STX) etc are lost.

编辑:我不想处理字符串,因为有可能出现不可打印的字节,而且我不能丢失这些数据。它需要是字节数组 :( 每当我转换为字符串时, 01 (SOH) 02 (STX) 等字节都会丢失。

Edit 2: Just to clarify. DO I lose data if I convert byte arrays to Strings? Now a little confused. What about if the bytes are of a different character set?

编辑2只是为了澄清。如果我将字节数组转换为字符串,我会丢失数据吗?现在有点糊涂了。如果字节是不同的字符集呢?

回答by lukastymo

  • change bytes to string
  • call text = text.replaceAll("\\s+$", ""); // remove only the trailing white space
  • change string to bytes
  • 将字节更改为字符串
  • 称呼 text = text.replaceAll("\\s+$", ""); // remove only the trailing white space
  • 将字符串更改为字节

回答by Vladislav Kysliy

Modification String trim()for byte[]. It cuts not only a tail of array but head too.

修改字符串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;
}

回答by digitaljoel

Easiest way? No guarantees on efficiency or performance, but it seems pretty easy.

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

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

回答by lynks

String s = new String(arrayWithWhitespace);
s = s.trim();
byte[] arrayWithoutWhitespace = s.getBytes();