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 use 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.

Step1:- Create the main getChar() which takes a string parameter and uses a for loop to iterate over the string length using charAt() method.
Step2:- Initialize a string and call the getChar() method.

public class Main {

   public static void getChar(String string) {
      for (int i = 0; i < string.length(); i++) {
         System.out.print(string.charAt(i) + " ");
      }
   }

   public static void main(String[] args) {
      String string = "Java Programming";
      getChar(string);
   }
}

Output:-

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

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 getChar(String str) {
      CharacterIterator itrator = new StringCharacterIterator(str);

      while (itrator.current() != CharacterIterator.DONE) {
         System.out.print(itrator.current() + " ");
         itrator.next();
      }
   }

   public static void main(String[] args) {
      String string = "Java Programming";
      getChar(string);
   }
}

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.