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.
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.
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.
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