Java loop over string code example
Example 1: java iterate over a string
String scientistName = "Isaac Newton";
for (int i = 0; i < scientistName.length(); i++) {
System.out.print(scientistName.charAt(i) + " "); // I s a a c N e w t o n
}
//*********************************************************
// you can cast a string into a char[]
String str = "strings are not primitive types!";
for (char ch : str.toCharArray()) {
System.out.print(scientistName.charAt(i) + " ");
}
}
Example 2: iterate over string java
String str = "hello";
for (char c : str.toCharArray())
//process c
Example 3: java loop through string
String s = "...stuff...";
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
//Process char
}
Example 4: Java loop over string
String s = "Techie Delight";
// convert string to `char[]` array
char[] chars = s.toCharArray();
// iterate over `char[]` array using enhanced for-loop
for (char ch: chars) {
System.out.print(ch);
}