How to Iterate through String Java

How to iterate Through String Java? In this section, we will discuss how can you iterate through a string in Java. We will write a Java program to iterate through string Java and to iterate over the string we can use loops.

To achieve the task we have two ways:-
1) Using iterators
2) Using loops

Iterate Through Characters In a String Java

Let us see how to iterate through String In Java using for loop. Usually to iterate an array or string elements we use for loop. It keeps on looping until the condition is satisfied. To iterate over the string length we can use the charAt() method.

public class Main {
    public static void main(String[] args) {
        String string = "Java";
        for (int i = 0; i < string.length(); i++) {
            System.out.println(string.charAt(i));
        }
    }
}

Output:-

J
a
v
a

public class Main {
    public static void main(String[] args) {
        String string = "Java Programming";
        for (int i = 0; i < string.length(); i++) {
            System.out.print(string.charAt(i));
        }
    }
}

Output:-

Java Programming

Iterate through String Java using Iterators

Let us see how to iterate through characters in a string Java using iterators. See the below code.

The object that is used to loop through the collections like ArrayList, HashSet and more is called an iterator. we call it an iterator because the technical term for looping is iterate.

In the below code, we need to import CharacterIterator and StringCharacterIterator. The text is an interface that is used to get the character in the string. The StringCharacterIterator sets the index of the iterator to 0.

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

public class Main {
    public static void main(String[] args) {
        String string = "Java Programming";
        CharacterIterator itrator = new StringCharacterIterator(string);
        while (itrator.current() != CharacterIterator.DONE) {
            System.out.print(itrator.current() + " ");
            itrator.next();
        }
    }
}

Output:-

J a v a P r o g r a m m i n g

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *