Created
November 3, 2013 09:27
-
-
Save esuomi/7288373 to your computer and use it in GitHub Desktop.
Iterates through a given `String` in unicode compatible way character by character.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package text; | |
import java.util.Iterator; | |
/** | |
* <p>Fun fact, this actually already exists in <code>sun.text.CodePointIterator</code></p> | |
* | |
* @author Esko Suomi <[email protected]> | |
* @since 31.8.2013 | |
*/ | |
public class CodePointIterator implements Iterator<Integer> { | |
private final String s; | |
private final int length; | |
private int offset = 0; | |
public CodePointIterator(String s) { | |
if (s == null) throw new IllegalArgumentException("String cannot be null"); | |
this.s = s; | |
this.length = s.length(); | |
} | |
@Override | |
public boolean hasNext() { | |
return offset < length; | |
} | |
@Override | |
public Integer next() { | |
int currentCodePoint = s.codePointAt(offset); | |
offset += Character.charCount(currentCodePoint); | |
return currentCodePoint; | |
} | |
@Override | |
public void remove() { | |
throw new UnsupportedOperationException("Cannot remove code point from processed String: Strings are immutable"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment