View Full Version : Java iterators
swappo1
October 21st, 2009, 07:37 PM
Does Java have iterators for strings like C++?
Reiger
October 21st, 2009, 08:36 PM
Not directly but a String can be converted to a char array which can be accessed using the for-each syntax:
public void test(String test) {
for(Character c: test.toCharArray()) {
System.out.println(c);
}
}
Gwasanaethau
October 22nd, 2009, 03:30 AM
You could also do:
public void test(String test) {
for(int i = 0; i < test.length(); i++) {
System.out.println(test.charAt(i));
}
}
Though I guess this does a conversion from a String to a char at every iteration of the for loop, where the previous example only converts once at the for loop's initialisation. However, I thought I'd add it nonetheless.
geirha
October 22nd, 2009, 05:51 AM
There's http://java.sun.com/javase/6/docs/api/java/text/StringCharacterIterator.html
Powered by vBulletin® Version 4.2.2 Copyright © 2024 vBulletin Solutions, Inc. All rights reserved.