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?
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);
[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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With