Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Trimming trailing whitespace from a byte array

Tags:

java

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.

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?

like image 278
Dominic Bou-Samra Avatar asked Oct 05 '11 23:10

Dominic Bou-Samra


1 Answers

Without converting to a string:

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

Tests:

like image 76
Matt Ball Avatar answered Sep 20 '22 21:09

Matt Ball