Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a string inside a bytebuffer

I'm switching from C to Java. I'm wondering about how to find a string inside a bytebuffer, is there something like memchr in java? The bytebuffer is only partly a string, the rest is raw bytes so any java method has to work on bytes + chars.

I am also searching for something like strsep in java to split strings.

like image 905
Blub Avatar asked Dec 28 '22 08:12

Blub


2 Answers

You can convert the ByteBuffer into a String and use indexOf which likely to work.

ByteBuffer bb = /* non-direct byte buffer */
String text = new String(bb.array(), 0, bb.position(), bb.remaing());
int index = text.indexOf(searchText);

This has a non-trivial overhead as it creates a String. The alternative is a brute force String search which will be faster but takes time to write.

like image 162
Peter Lawrey Avatar answered Dec 30 '22 11:12

Peter Lawrey


You would need to encode the character string into bytes using the correct character encoding for your application. Then use a string search algorithm like Rabin-Karp or Boyer-Moore to find the resulting byte sequence within the buffer. Or, if your buffers are small, you could just perform a brute force search.

I'm not aware of any open source implementations of these search algorithms, and they aren't part of core Java.

like image 31
erickson Avatar answered Dec 30 '22 09:12

erickson