Java:如何从 String 中获取 Iterator<Character>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3925130/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 07:00:35  来源:igfitidea点击:

Java: how to get Iterator<Character> from String

javastringiterator

提问by Albert

I need a Iterator<Character>from a Stringobject. Is there any available function in Java that provides me this or do I have to code my own?

我需要Iterator<Character>一个String对象。Java 中是否有任何可用的功能可以为我提供此功能,还是我必须自己编写代码?

采纳答案by ColinD

One option is to use Guava:

一种选择是使用Guava

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).

这会产生一个由给定字符串支持的不可变字符列表(不涉及复制)。

If you end up doing this yourself, though, I would recommend not exposing the implementation class for the Iteratoras a number of other examples do. I'd recommend instead making your own utility class and exposing a static factory method:

但是,如果您最终自己这样做,我建议不要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();
    }
  };
}

回答by Qwerky

Not sure if there is a more direct way but you could do something like;

不确定是否有更直接的方法,但您可以这样做;

Arrays.asList(string.toCharArray()).iterator();
Arrays.asList(string.toCharArray()).iterator();

Scratch that; Arrays.asList doesn't do what I seem to remember it doing.

抓那个;Arrays.asList 没有做我似乎记得它在做的事情。

Edit 2: Seems like it last worked this way in 1.4

编辑 2:似乎它最后在 1.4 中以这种方式工作

回答by virgium03

CharacterIterator it = new StringCharacterIterator("abcd"); 
// Iterate over the characters in the forward direction 
for (char ch=it.first(); ch != CharacterIterator.DONE; ch=it.next())
// Iterate over the characters in the backward direction 
for (char ch=it.last(); ch != CharacterIterator.DONE; ch=it.previous()) 

回答by Damian Leszczyński - Vash

The Iteratoriterate over a collection or whatever implements it. String class does nost implement this interface. So there is no direct way.

迭代器遍历整个集合或任何实现它。String 类没有实现这个接口。所以没有直接的方法。

To iterate over a string you will have to first create a char array from it and then from this char array a Collection.

要迭代一个字符串,您必须首先从它创建一个字符数组,然后从这个字符数组创建一个集合。

回答by aioobe

It doesn't exist, but it's trivial to implement:

它不存在,但实现起来很简单:

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();
    }
}

The implementation is probably as efficient as it gets.

实现可能是最有效的。

回答by cyber-monk

Short answer: No, you have to code it.

简短回答:不,您必须对其进行编码。

Long answer: List and Set both have a method for obtaining an Iterator(there are a few other collection classes, but probably not what your looking for). The List and Set interfaces are a part of the Collections Frameworkwhich only allow for adding/removing/iterating Objects like Character or Integer (not primitives like char or int). There is a feature in Java 1.5 called auto-boxingthat will hide this primitive to Object conversion but I don't recommend it and it won't provide what you want in this case.

长答案:List 和 Set 都有一个获取迭代器的方法(还有一些其他的集合类,但可能不是你想要的)。List 和 Set 接口是集合框架的一部分,它只允许添加/删除/迭代像 Character 或 Integer 这样的对象(而不是像 char 或 int 这样的原语)。Java 1.5 中有一个称为自动装箱的功能,它将隐藏此原语到对象的转换,但我不推荐它,并且在这种情况下它不会提供您想要的。

An alternative would be to wrap the String in a class of your own that

另一种方法是将 String 包装在您自己的类中

implements Iterator<Character>

but that might be more work than it is worth.

但这可能比它的价值更多。

Here is a code snippet for doing what you want:

这是执行您想要的操作的代码片段:

String s = "";
List<Character> list = new ArrayList<Character>(s.length());
for (int i = 0; i < s.length(); i++) {
    // note that Character.valueOf() is preferred to new Character()
    // you can omit the Character.valueOf() method
    // and Java 1.5+ will auto-box the primitive into an Object
    list.add(Character.valueOf(s.charAt(i)));
}
Iterator<Character> iterator = list.iterator();

回答by leonbloy

No direct way. Not difficult to code, though:

没有直接的办法。不过编码并不难:

public static Iterator<Character> gimmeIterator(final String x) {
        Iterator<Character> it = new Iterator<Character>() {
            String str = x == null ? "" : x;
            int pos = -1; // last read
            public boolean hasNext() {  return(pos+1 <  str.length());  }
            public Character next() { pos++;  return str.charAt(pos);       }
            public void remove() {
                throw new UnsupportedOperationException("remove unsupported for this iterator");
            }
        };  
        return it;
    }

回答by Lee

Stealing from somebody else in another answer, this is probably the best direct implementation (if you're not going to use guava).

在另一个答案中从其他人那里窃取信息,这可能是最好的直接实现(如果您不打算使用番石榴)。

/**
 * @param string
 * @return list of characters in the string
 */
public static List<Character> characters(final String string) {
return new AbstractList<Character>() {
        @Override
    public Character get(int index) {
            return string.charAt(index);
        }

        @Override
    public int size() {
            return string.length();
        }
    };
}

回答by user1680517

for (char c : myString.toCharArray()) {

}

回答by wool.in.silver

This can be done with a little help from Apache Commons Lang (if you don't want to use Guava, and want a true java.util.Iterator.

这可以在 Apache Commons Lang 的帮助下完成(如果您不想使用 Guava,并且想要一个真正的java.util.Iterator.

private static Iterator<Character> iterator(String string) {
    return Arrays.asList(ArrayUtils.toObject(string.toCharArray())).iterator();
}