Skip to main content

scanning strings as iterables

No replies
vpatryshev
Offline
Joined: 2004-06-30
Points: 0

There are many solutions; I don't know, I don't find them beautiful; seems like mine is better:

public Iterable chars(CharSequence source);

so that you can write

for (char c : chars("This is a string")) {
// do something
}

So, below is the method... I've just included it to Iterators class at myjavatools.com:

<br />
  public static Iterable chars(final CharSequence sequence) {<br />
  return new Iterable() {<br />
      public Iterator iterator() {<br />
        return new Iterator() {<br />
          int index = 0;<br />
          public boolean hasNext() {<br />
            return index < sequence.length();<br />
          }<br />
          public void remove() {<br />
            throw new UnsupportedOperationException();<br />
          }<br />
          public Character next() {<br />
            return sequence.charAt(index++);<br />
          }<br />
        };<br />
      }<br />
    };<br />
  }</p>
<p>