3
\$\begingroup\$

Given this piece of code, what is a better way to write it (cleaner). It is taken for granted that data will not be null, nor its length will be 0, so this check is skipped.

private byte[] process(byte[] bytes) {
 int from = 0;
 if (bytes[0] == '\n') {
 from = 1;
 } else if (bytes[0] == '\r' && bytes[1] == '\n') {
 from = 2;
 }
 return Arrays.copyOfRange(bytes, from, bytes.length);
}

I thought about converting it to String, then applying a regex (^[\r\n]), but that means some encoding has to be used for the conversion and then I would have to convert it back to byte[], which does not comply with my needs. Is there any clearer way to write this?

asked Jul 6, 2018 at 11:00
\$\endgroup\$
1
  • 1
    \$\begingroup\$ To whoever down-voted and close-voted this question, I don't see how the author is asking for help fixing broken code. \$\endgroup\$ Commented Jul 6, 2018 at 11:03

1 Answer 1

2
\$\begingroup\$

I don't think you can make this specifically better.

What you could do is make the function more generic, but that depends on what your data contains beyond the first two bytes. For example, you could simply skip any and all line feeds and carriage returns at the beginning:

private int skipLFandCR(byte[] bytes) {
 int pos = 0;
 while (pos < bytes.length && (bytes[pos] == '\r' || bytes[pos] == '\n')) {
 pos++;
 }
 return pos;
}

Also: Do you need a copy of the data? I'd just use a function that returns the start index such as mine and process the existing array starting at that index.

answered Jul 6, 2018 at 11:48
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.