[英]Is it possible to set the position of a Java CharBuffer?
我想要做的事情有点回填。
我想解析一个String,但是为了能够比较,例如
失败了
等等
继续,直到我得到一场比赛,或EOS。
使用数组很容易做到这一点但我想在一个方法中执行此操作并返回一个带有索引的缓冲区,该索引指向下一个开始处理的位置。 我被引导相信CharBuffer是一个很好的解决方案,但我不确定。
编辑通过一个例子 - 不完全可编译的代码!
主要
List template1 = new List();
List template2 = new List();
String exampleInput = "oneone two";
template1.add ( "one" );
template1.add ( "two" );
template1.add ( "three" );
template2.add ( "one" );
template2.add ( "one" );
template2.add ( "two" );
Set templates = new Set();
templates.add ( template1 );
templates.add ( template2 );
NoisyParser np = new NoisyParser();
np.parse( templates, exampleInput );
NoisyParser
void parse( Set templates, Sting inp ){
iterate over each template that matches inp{
find_match( template, inp );
}
}
boolean find_match( template, inp ) {
This is where I need the magic to work out if the current element
in template matches the current position of inp, or inp+1, give or take.
}
CharBuffer
有一个内部索引,你可以从中进行相对读取,所以是的,它应该适合你的标准。
您可以使用(继承的) Buffer.position(int newPosition)
方法设置位置。
您还可以mark
位置,并reset
为上一个标记。
由于来自NIO包的类通常用于(并且用于)I / O,我鼓励您考虑在类中包装char[]
和int pos
:
class PositionableCharArray {
int pos;
char[] chars;
...
public void setPos(int pos) { ... }
public char readChar() { return chars[pos++]; }
}
那么你可以使用Buffer.charAt(int)
来实现这个,以获取相对于当前位置的字符,并使用Buffer.get()
来提前当前位置。 或者您可以使用Buffer
操作来操纵位置。
但我认为你最好实现自己的类,将字符读入char[]
(或String
),并提供执行所需原语操作的方法。 您可以使用CharBuffer
获得更高性能的解决方案,但可能性不会成为性能瓶颈。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.