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();
}
};
}
相关文章