Alb*_*ert 33 java string iterator
我需要Iterator<Character>一个String物体.Java中是否有任何可用的功能可以为我提供这个功能,还是我必须编写自己的代码?
Col*_*inD 30
一种选择是使用番石榴:
ImmutableList<Character> chars = Lists.charactersOf(someString);
UnmodifiableListIterator<Character> iter = chars.listIterator();
Run Code Online (Sandbox Code Playgroud)
这将生成一个由给定字符串支持的不可变字符列表(不涉及复制).
但是,如果你最终自己这样做了,我建议不要Iterator像其他一些例子那样公开实现类.我建议改为创建自己的实用程序类并公开静态工厂方法:
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();
}
};
}
Run Code Online (Sandbox Code Playgroud)
aio*_*obe 18
它不存在,但实现起来很简单:
class CharacterIterator implements Iterator<Character> {
private final String str;
private int pos = 0;
public CharacterIterator(String str) {
this.str = str;
}
public boolean hasNext() {
return pos < str.length();
}
public Character next() {
return str.charAt(pos++);
}
public void remove() {
throw new UnsupportedOperationException();
}
}
Run Code Online (Sandbox Code Playgroud)
实现可能和它一样有效.
小智 11
for (char c : myString.toCharArray()) {
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37393 次 |
| 最近记录: |