我需要一个来自 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模板网!
Java从数组中删除重复项?Java Remove Duplicates from an Array?(Java从数组中删除重复项?)
如何修复调用失败来自服务器的意外响应:在 AnHow to fix Invocation failed Unexpected Response from Server: Unauthorized in Android studio(如何修复调用失败来自服务器的意外响应:在
AES 加密,解密文件中有多余的垃圾字符AES encryption, got extra trash characters in decrypted file(AES 加密,解密文件中有多余的垃圾字符)
AES 错误:给定的最终块未正确填充AES Error: Given final block not properly padded(AES 错误:给定的最终块未正确填充)
在 JAVA 中使用 AES/GCM 检测不正确的密钥Detecting incorrect key using AES/GCM in JAVA(在 JAVA 中使用 AES/GCM 检测不正确的密钥)
Java 中的 AES-256-CBCAES-256-CBC in Java(Java 中的 AES-256-CBC)