繁体   English   中英

是否可以设置Java CharBuffer的位置?

[英]Is it possible to set the position of a Java CharBuffer?

我想要做的事情有点回填。

我想解析一个String,但是为了能够比较,例如

  • x位置的1个字符
  • 位置x处的2个字符
  • ...
  • 在位置x的n个字符

失败了

  • 位置x + 1处的1个字符
  • 位置x + 1的2个字符
  • ...
  • 位于x + 1的n个字符

等等

继续,直到我得到一场比赛,或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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM