【问题标题】:Is it possible to set the position of a Java CharBuffer?是否可以设置 Java CharBuffer 的位置?
【发布时间】:2011-11-23 10:44:44
【问题描述】:

对我正在尝试做的事情进行一些补充。

我想解析一个String,但要能够比较,例如

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

失败了

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

继续直到我得到一个匹配,或 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 );

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

【问题讨论】:

  • 您的具体要求是什么?比较两个字符串并找到它们不匹配的第一个位置?还是比较 n 个字符串?
  • 这有点复杂,我有许多字符串列表,我想将它们与嘈杂的输入字符串进行匹配,看看哪个列表匹配,是任意的。
  • 我认为最好提供一个小例子。比如说,一个包含两个字符串的列表,另一个包含三个字符串和输入字符串的列表,然后指定您期望的结果究竟是什么。从帖子中很难理解您的确切要求。

标签: java arrays string parsing


【解决方案1】:

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++]; }
}

【讨论】:

  • 他不能重复使用java.text.ParsePosition吗?听起来就是为了这个。
  • 感谢您的回复,您的 PositionaleCharArray 和 CharBuffer 不就是我想要使用它们的方式吗?
  • 可能。 PositionableCharArray 将有一个更小的接口,这使得更容易确保一些不变量保持不变(chars 永远不会改变,0 pos chars.length 等等......)。例如,如果您将CharBuffer 传递给某个未来的方法,它认为clear 缓冲区会很方便。此外,由于该类具有更明确的目的,因此可以轻松阅读代码等。
【解决方案2】:

你可以使用Buffer.charAt(int) 来实现这个,以获取相对于当前位置的字符,并使用Buffer.get() 来推进当前位置。或者您可以使用Buffer 操作来操纵位置。

但我认为您最好实现自己的类,将字符读入char[](或String)并提供执行所需基本操作的方法。您可能使用CharBuffer 获得性能更高的解决方案,但这很可能不会成为性能瓶颈。

【讨论】:

  • 干杯,这似乎是共识。我可能最终会尝试将 Buffer 塞入我想要的内容中。
猜你喜欢
  • 2010-10-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-21
相关资源
最近更新 更多