Java - trimming trailing spaces from an array of bytes

I have byte arrays like this:

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

approximately equal

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

Now I want to trim the trailing spaces so that they look like this:

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

The easiest way to do this?

Change I do not want to deal with strings, because there is a possibility for non-printable bytes, and I can not afford to lose this data. These should be byte arrays :( Whenever I do a conversion to strings, bytes like 01 (SOH) 02 (STX), etc. are lost.

Edit 2 : Just for clarification. Am I losing data if I convert byte arrays to strings? Now a little confused. What if bytes have a different character set?

+9
java
source share
5 answers
+17
source share

The easiest way? There is no guarantee of efficiency or performance, but it looks pretty easy.

 byte[] results = new String(yourBytes).trim().getBytes(); 
+1
source share
  • change bytes to string
  • call text = text.replaceAll("\\s+$", ""); // remove only the trailing white space text = text.replaceAll("\\s+$", ""); // remove only the trailing white space
  • change string to bytes
0
source share

Modification string trim() for byte[] . He cuts not only the tail, but also the head.

 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; } 
0
source share
 String s = new String(arrayWithWhitespace); s = s.trim(); byte[] arrayWithoutWhitespace = s.getBytes(); 
-one
source share

All Articles