对我正在尝试做的事情进行一些回填。
我想解析一个String,但是要能够比较,比如
- 位置 x 处的 1 个字符
- 位置 x 处有 2 个字符
- ...
- n 个字符在位置 x
失败了
- 位置 x+1 处的 1 个字符
- 位置 x+1 处有 2 个字符
- ...
- n 个字符在位置 x+1
等等
继续,直到找到匹配项或 EOS。
用数组很容易做到这一点,但我想在一个方法中做到这一点,并返回一个缓冲区,其中的索引指向下一个开始处理的地方。我被引导相信 CharBuffer 是一个很好的解决方案,但我不确定。
EDIT 举例 - 不完全是可编译代码!
主要
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 );
噪音解析器
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)
设置位置方法。
您还可以标记
一个位置,然后重置
到之前的标记。
由于 NIO 包中的类通常用于(以及用于)I/O,我鼓励您考虑包装一个 char[]
和一个 int pos
在类里面:
class PositionableCharArray {
int pos;
char[] chars;
...
public void setPos(int pos) { ... }
public char readChar() { return chars[pos++]; }
}
关于java - 是否可以设置 Java CharBuffer 的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8240803/