How can I iterate through a string in Java?
I'm trying to use a foreach style for loop
for (char x : examplestring) {
    //action
}
How can I iterate through a string in Java?
I'm trying to use a foreach style for loop
for (char x : examplestring) {
    //action
}
 
    
     
    
    If you want to use enhanced loop, you can convert the string to charArray
for (char ch : exampleString.toCharArray()) {
  System.out.println(ch);
}
 
    
     
    
    Java Strings aren't character Iterable. You'll need:
for (int i = 0; i < examplestring.length(); i++) {
  char c = examplestring.charAt(i);
  ...
}
Awkward I know.
 
    
     
    
    Using Guava (r07) you can do this:
for(char c : Lists.charactersOf(someString)) { ... }
This has the convenience of using foreach while not copying the string to a new array. Lists.charactersOf returns a view of the string as a List.
 
    
    How about this
for (int i = 0; i < str.length(); i++) { 
    System.out.println(str.substring(i, i + 1)); 
} 
 
    
    