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

标签 java arrays string parsing

对我正在尝试做的事情进行一些回填。

我想解析一个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/

相关文章:

javascript 获取最后一个重复值索引 javascript

javascript - 有什么方法可以更改数组元素索引,使其从 1, 2, 3, 4 而不是 0, 1 ,2, 3 开始?

java - Spring Integration 在有效负载表达式中组合路径变量和发布主体

java - 如何在没有比较器的情况下使用java中的MergeSort对对象数组进行排序

java - Web 服务互操作性

c++ - vector 的迭代器---测试结束

string - 计算可重复长度为 n 的二进制字符串的个数

MySQL 字符串中多次出现相同的字母

c - 如何将 unsigned char* 转换为 char*

java - 如何将命令行输入文件中的行打印到命令行输出文件?