Programming Tips - Java: How can I iterate through a String?

Date: 2013nov7 Updated: 2020nov23 Language: Java Q. Java: How can I iterate through a String? A. There are several resaonable ways. Use charAt()
String s = "Hello World"; for (int i = 0; i < s.length(); i++) { final char c = s.charAt(i); // Do something with c }
Use toCharArray()
for (final char c : s.toCharArray()) { // Do something with c }
Use getBytes()
for (final byte b : s.getBytes() { // Do something with c }
Some guy compared all the possible ways for speed: http://stackoverflow.com/questions/8894258/fastest-way-to-iterate-over-all-the-chars-in-a-string