[adapted from Josh and Neal's "cooking with Tiger" talk]
Placing the enclosed adapter method in java.lang.String enables clients to
iterate through the code points in a String very easily:
void f(String s) {
for (int ch : s.codePoints())
;// do something with the codepoint ch here.
}
Here is the proposed addition to java.lang.String:
public Iterable<Integer> codePoints() {
return new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
int nextIndex = 0;
public boolean hasNext() {
return nextIndex < length();
}
public Integer next() {
int result = codePointAt(nextIndex);
nextIndex += Character.charCount(result);
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
Placing the enclosed adapter method in java.lang.String enables clients to
iterate through the code points in a String very easily:
void f(String s) {
for (int ch : s.codePoints())
;// do something with the codepoint ch here.
}
Here is the proposed addition to java.lang.String:
public Iterable<Integer> codePoints() {
return new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
int nextIndex = 0;
public boolean hasNext() {
return nextIndex < length();
}
public Integer next() {
int result = codePointAt(nextIndex);
nextIndex += Character.charCount(result);
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
- duplicates
-
JDK-6275004 String and StringBuffer should be allowed in 'foreach' construct
-
- Closed
-
-
JDK-8012665 CharSequence.chars, CharSequence.codePoints
-
- Closed
-
- relates to
-
JDK-5063163 (str) Please add a method int[] String.toCodePointArray()
-
- Closed
-