問(wèn)題描述
我需要一個(gè)來(lái)自 String
對(duì)象的 Iterator<Character>
.Java 中是否有任何可用函數(shù)可以為我提供此功能,還是我必須自己編寫(xiě)代碼?
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();
這會(huì)生成一個(gè)由給定字符串支持的不可變字符列表(不涉及復(fù)制).
This produces an immutable list of characters that is backed by the given string (no copying involved).
如果您最終自己這樣做,我建議不要像許多其他示例那樣公開(kāi) Iterator
的實(shí)現(xiàn)類(lèi).我建議改為創(chuàng)建自己的實(shí)用程序類(lèi)并公開(kāi)靜態(tài)工廠方法:
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();
}
};
}
這篇關(guān)于Java:如何獲取迭代器<字符>從字符串的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!