How to Iterate Over Characters of String in JAVA

Are you looking to iterate over characters of String in JAVA? In this post, I will discuss what are the best ways you can iterate over the string for either characters or words in JAVA.

In this post, I will discuss around four most efficient methods that you can use to iterate over characters of String. Also, I will show the example codes that you can make use of to learn.

1. Using charAt Method: The Naive Approach

The most basic way to iterate in JAVA over the characters of String is using the charAt method that is defined in the String Class of JAVA.

This method helps you convert the currently given string to a character at a given index. You can use a for loop to iterate over the string’s length (in this case, N – 1) and then output str[i] each time you iterate the loop.

Let us see the example code below.

public class Solution {

   public static void main(String args[]) {
       //Initializing String to Iterate Over
       String givenString = "Coduber.com";

       for(int i=0; i < givenString.length(); i++){

        //Printing Each Character of the Given String using chartAt
           System.out.print(givenString.charAt(i) + " ");

       }
   }
}

Output:

C o d u b e r . c o m
Time Complexity: O(N)
Auxiliary Space: O(1)

This is the method at is the most efficient method available in JAVA to iterate over characters and this is what I recommend you to use.

How to Iterate Over Characters of String in JAVA

2. Using toCharArray Method of String Class

In this approach, we convert string to a character array using String.toCharArray() method. Then iterate the character array using for loop or for-each loop.

This can also be considered one of the naive approaches. In this, you can either directly convert the given string to a character array or create a new character array variable to store the converted string and then iterate over it.

The second approach is not recommended as it will create an extra space complexity for your program. Let us see this in below example code below to understand it.

import java.nio.channels.GatheringByteChannel;

public class Solution {

   public static void main(String args[]) {
       //Initializing String to Iterate Over
       String givenString = "Coduber.com";

        //Creating a Character Array to Hold the Conversion
        char[] characterArray = givenString.toCharArray();

        for(int i = 0; i< characterArray.length; i++){

            System.out.print(characterArray[i] + " ");

        }
        System.out.println("\n");

        //Printing the givenString by Directly Converting and not
        //Saving it in character Array

        for(char charInString:givenString.toCharArray()){
            System.out.print(charInString + " ");
        }

   }
}

Output:

C o d u b e r . c o m 

C o d u b e r . c o m 

3. Using forEach or forEachOrdered Method From codePoints()

You can use the forEach or forEachOrdered Method to iterate over the characters of the given string. This method should be used when you are going to use codepoints in your Code and also you are using JAVA version 8 or higher.

Note here forEachOrdered gives you the assurance that order will be maintained while iterating through character but the same is not assured when you are using forEach only.

Let us see in the below example code the usage of forEach and forEachOrdered Method.

public class Solution {

   public static void main(String args[]) {
       //Initializing String to Iterate Over
       String givenString = "Coduber.com";

       //Using forEach Method of codePoints
       givenString.codePoints().forEach(i -> System.out.print((char)i + " "));

       System.out.println();

       //Using forEachOrdered Method of codePoints
       givenString.codePoints().forEachOrdered(i -> System.out.print((char)i + " "));
   }
}

Output:

C o d u b e r . c o m 
C o d u b e r . c o m 

As you can see using the above code I was successfully able to iterate through characters of the string.

4. Using Split Method of String Class

You can use the split method present in the String class of JAVA. If you use an empty string as a regex inside the split method then it will split the characters of the string into an array of String Characters.

Then You can use the For loop to iterate through all the characters of the String and print it. Let us see this in below example code.

public class Solution {

   public static void main(String args[]) {
       //Initializing String to Iterate Over
       String givenString = "Coduber.com";

       String[] characterArray = givenString.split("");

       for(String c:characterArray)
        System.out.print(c + " ");
   }
}

Output:

C o d u b e r . c o m 

Wrap Up

I hope you were able to find the solution to the problem of how to iterate over characters of a string. From all the methods discussed above, The Most efficient and recommended method is charAt() i.e the first method from the above list.

As based upon our testing we found that charAt() method took the least amount of execution time when compared to any other methods available over the internet.

Let me know if you have any better and efficient method in the comment section I will be happy to add it here.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. JAVA: Meaning of \n and \t With Examples
  2. JAVA String to Int Complete Guide JAVA 8
  3. How To Return Null in Python Discussed
  4. How to Split a String into a List of Words or Letters in Python
  5. Reading A Binary File In Python With Examples

Leave a Reply

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