Ask Your Question
2

How can trailing whitespace be removed from a byte array in Java?

asked 2022-04-21 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-12-09 09:00:00 +0000

lakamha gravatar image

One way to remove trailing whitespace from a byte array in Java is to use the trim() method of the String class. This can be done as follows:

byte[] originalBytes = ...; // the original byte array
String str = new String(originalBytes).trim();
byte[] trimmedBytes = str.getBytes();

Explanation:

  1. Convert the byte array to a string using the String(byte[]) constructor.
  2. Use the trim() method to remove the trailing whitespace from the string.
  3. Convert the resulting string back to a byte array using the getBytes() method. The resulting byte array will not contain trailing whitespace.
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-21 11:00:00 +0000

Seen: 17 times

Last updated: Dec 09 '21