Java:如何获取迭代器<字符>从字符串

时间:2023-01-14
本文介绍了Java:如何获取迭代器<字符>从字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要一个来自 String 对象的 Iterator<Character>.Java 中是否有任何可用函数可以为我提供此功能,还是我必须自己编写代码?

I need a Iterator<Character> from a String object. Is there any available function in Java that provides me this or do I have to code my own?

推荐答案

一种选择是使用 番石榴:

ImmutableList<Character> chars = Lists.charactersOf(someString);
UnmodifiableListIterator<Character> iter = chars.listIterator();

这会生成一个由给定字符串支持的不可变字符列表(不涉及复制).

This produces an immutable list of characters that is backed by the given string (no copying involved).

如果您最终自己这样做,我建议不要像许多其他示例那样公开 Iterator 的实现类.我建议改为创建自己的实用程序类并公开静态工厂方法:

If you end up doing this yourself, though, I would recommend not exposing the implementation class for the Iterator as a number of other examples do. I'd recommend instead making your own utility class and exposing a static factory method:

public static Iterator<Character> stringIterator(final String string) {
  // Ensure the error is found as soon as possible.
  if (string == null)
    throw new NullPointerException();

  return new Iterator<Character>() {
    private int index = 0;

    public boolean hasNext() {
      return index < string.length();
    }

    public Character next() {
      /*
       * Throw NoSuchElementException as defined by the Iterator contract,
       * not IndexOutOfBoundsException.
       */
      if (!hasNext())
        throw new NoSuchElementException();
      return string.charAt(index++);
    }

    public void remove() {
      throw new UnsupportedOperationException();
    }
  };
}

这篇关于Java:如何获取迭代器&lt;字符&gt;从字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:是一个“无限"的迭代器设计不好? 下一篇:在同一个类中实现 Java Iterator 和 Iterable?

相关文章

最新文章