我正在从C转向Java。我想知道如何在ByteBuffer中查找字符串,是否有类似于java中的memchr的方法?ByteBuffer仅部分为字符串,其余为原始字节,因此任何Java方法都必须在字节和字符上工作。
我还在寻找类似于Java中的strsep来拆分字符串的方法。
我正在从C转向Java。我想知道如何在ByteBuffer中查找字符串,是否有类似于java中的memchr的方法?ByteBuffer仅部分为字符串,其余为原始字节,因此任何Java方法都必须在字节和字符上工作。
我还在寻找类似于Java中的strsep来拆分字符串的方法。
ByteBuffer bb = /* non-direct byte buffer */
String text = new String(bb.array(), 0, bb.position(), bb.remaing());
int index = text.indexOf(searchText);
这个操作会创建一个字符串,因此会产生一些开销。另一种方法是使用暴力字符串搜索,速度更快但需要花费一定时间编写代码。
String text = new String(bb.array(), 0, bb.position(), charset);
其中 charset
是要使用的编码或默认编码 Charset.defaultCharset()
。 - mins我在MIMEParser中找到的最佳实现:https://github.com/samskivert/ikvm-openjdk/blob/master/build/linux-amd64/impsrc/com/sun/xml/internal/org/jvnet/mimepull/MIMEParser.java
/**
* Finds the boundary in the given buffer using Boyer-Moore algo.
* Copied from java.util.regex.Pattern.java
*
* @param mybuf boundary to be searched in this mybuf
* @param off start index in mybuf
* @param len number of bytes in mybuf
*
* @return -1 if there is no match or index where the match starts
*/
private int match(byte[] mybuf, int off, int len) {
private void compileBoundaryPattern();
StringTokenizer
,它可以根据给定的分隔符将字符串拆分为可迭代的令牌集合。如果需要,令牌集合可以包含分隔符。例如:String s = "abc:def-ghi|jkl";
StringTokenizer tokenizer = new StringTokenizer(s, ":-|");
while (tokenizer.hasMoreTokens()) {
System.out.print(tokenizer.nextToken());
}
abcdefghijkl
String.split()
函数来分割字符串。 - juergen d