This wikiHow teaches you how to iterate through the characters of a string in Java. The simplest way to do this is to create a for-loop with the charAt() method.

Steps

  1. 1
    Create a string. The string will contain the characters you want to parse. In our example, we'll be creating code that evaluates and prints each character of the string to the screen. To begin, let's call our string wikiHow:
    class Main {
    public static void main(String[] args) {
    // this creates a string called wikiHow
      	String name = "wikiHow";
       	System.out.println("Characters in " + name + " are:");
    }
    }
    
  2. 2
    Begin your for-loop. The for-loop will access each element of the string.[1] You'll start by writing the "for" part of the structure:
    class Main {
    public static void main(String[] args) {
        	// this creates a string called wikiHow
       	 String name = "wikiHow";
        	System.out.println("Characters in " + name + " are:");
       	// loop through each element
       	 for(int i = 0; i<name.length(); i++) {
    }
    }
    
    Advertisement
  3. 3
    Add the charAt() method to your for loop. This part of the for-loop will evaluate each character in the string based on the elements found and print them to the screen.
    class Main {
    public static void main(String[] args) {
        	// this creates a string called wikiHow
        	String name = "wikiHow";
        	System.out.println("Characters in " + name + " are:");
       	// loop through each element
        	for(int i = 0; i<name.length(); i++) {
    // access each character
         			char a = name.charAt(i);
        			System.out.print(a + ", ");
    }
    }
    }
    
    Advertisement

About This Article

Nicole Levine, MFA
Co-authored by:
Tech Specialist
This article was co-authored by Nicole Levine, MFA. Nicole Levine is a Technology Writer and Editor for wikiHow. She has more than 20 years of experience creating technical documentation and leading support teams at major web hosting and software companies. Nicole also holds an MFA in Creative Writing from Portland State University and teaches composition, fiction-writing, and zine-making at various institutions. This article has been viewed 1,458 times.
How helpful is this?
Co-authors: 3
Updated: February 12, 2021
Views: 1,458
Categories: Java
Article SummaryX

1. Create a string.
2. Create a for-loop containing a char() method.

Did this summary help you?
Advertisement