How I can read in blocks from InputStream to chars[] until 4 specific chars?
I'm reading the input byte by byte, but complex condition of an exit from while turns out. And reading blocks more efficiently.
int p0 = stream.read(),
p1 = stream.read(),
p2 = stream.read(),
p3 = stream.read();
while (!(p0 == a && p1 == b && p2 == c && p3 == d)) {
result[i] = (char) p0;
p0 = p1;
p1 = p2;
p2 = p3;
p3 = stream.read();
i++;
}
Rather than reading character by character, create a larger buffer and use a variant of InputStream#read(buffer[], offset, length) to fill the buffer. The following function will efficiently determine the starting location of a 4 character match, or return -1 if none is found. The result then is the sequence of characters (in the buffer) from position 0 to getIndex(buf)-1.
// Will determine the starting index of the 4 specific characters (or -1)
int getIndex(char buf[]) {
char c4='z';
char c3='y';
char c2='x';
char c1='w';
int tail = 3;
while (tail < buf.length) {
if (buf[tail] == c4 && buf[tail-1] == c3 && buf[tail-2] == c2 && buf[tail-3] == c1)
return tail-3;
tail++;
}
return -1;
}
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