Java - Trimming trailing whitespace from a byte array
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:
[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]
Easiest way? No guarantees on efficiency or performance, but it seems pretty easy.
byte[] results = new String(yourBytes).trim().getBytes();