Iterating Over the Characters of a String - Java Language Basics

Java examples for Language Basics:String

Solution 1

Use String methods to gain access to the String at a character level.

String str = "Break down into chars"; 
System.out.println(str); 
for (char chr:str.toCharArray()){ 
    System.out.println(chr); 
} 

Solution 2

Access to each character of the String using the charAt() method.

for (int x = 0; x <= str.length()-1; x++){ 
   System.out.println(str.charAt(x)); 
} 

Demo Code

public class Main {    
    public static void main(String[] args){
        String str = "Break down into chars";
        System.out.println(str);/*from w ww  .java 2 s  . co  m*/
        
        for (char chr:str.toCharArray()){
            System.out.println(chr);
        }
        
        for (int x = 0; x <= str.length()-1; x++){
            System.out.println(str.charAt(x));
        }
    }
}

Result


Related Tutorials