本文介紹了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:如何獲取迭代器<字符>從字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!