The Wayback Machine - https://web.archive.org/web/20241002014849/https://www.geeksforgeeks.org/iterate-over-the-characters-of-a-string-in-java/
Open In App

Iterate Over the Characters of a String in Java

Last Updated : 28 Feb, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given string str of length N, the task is to traverse the string and print all the characters of the given string.

Illustration:

Input  : “GeeksforGeeks”
Output : G e e k s f o r G e e k s
Input. : “Coder”
Output : C o d e r

Methods:

  1. Using Naive Approach
  2. Using String.toCharArray() method
  3. Using CharacterIterator
  4. Using StringTokenizer
  5. Using String.split() method
  6. Using Guava Library
  7. Using String.chars() method
  8. Using Code Points

Method 1: Naive Approach

The simplest approach to solve this problem is to iterate a loop over the range [0, N – 1], where N denotes the length of the string, using the variable i and print the value of str[i].

Example 

Java




// Java Program to Iterate Over the Characters of a String
// Using Naive Approach
 
// Importing classes from respective packages
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Method 1
    // Function to traverse the string and
    // print the characters of the string
    static void traverseString(String str)
    {
        // Traverse the string
        for (int i = 0; i < str.length(); i++) {
 
            // Print current character
            System.out.print(str.charAt(i) + " ");
        }
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "GeeksforGeeks";
 
        // Calling the Method 1
        traverseString(str);
    }
}


Output

G e e k s f o r G e e k s 

Time Complexity: O(N)
Auxiliary Space: O(1)

Method 2: Using String.toCharArray() method

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.

Example 

Java




// Java Program to Iterate Over the Characters of a String
// Using String.toCharArray() method
 
// Importing classes from respective packages
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Method 1
    // To traverse the string and
    // print the characters of the string
    static void traverseString(String str)
    {
        char[] ch = str.toCharArray();
 
        // Traverse the character array
        for (int i = 0; i < ch.length; i++) {
 
            // Print current character
            System.out.print(ch[i] + " ");
        }
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "GeeksforGeeks";
 
        // Calling the Method 1
        traverseString(str);
    }
}


Output

G e e k s f o r G e e k s 

Time Complexity: O(N)
Auxiliary Space: O(N)

Method 3: Using CharacterIterator

In this approach, we use the CharacterIterator methods current() to get the current character and next() to move forward by one position. StringCharacterIterator provides the implementation of CharacterIterator.

Example  

Java




// Java Program to Iterate Over the Characters of a String
// Using CharacterIterator
 
// Importing required libraries
import java.io.*;
import java.text.*;
 
// Main class
class GFG {
 
    // Method 1
    // To traverse the string and
    // print the characters of the string
    static void traverseString(String str)
    {
        CharacterIterator it
            = new StringCharacterIterator(str);
 
        // Iterate and print current character
        while (it.current() != CharacterIterator.DONE) {
            System.out.print(it.current() + " ");
 
            // Moving onto next element in the object
            // using next() method
            it.next();
        }
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "GeeksforGeeks";
 
        // Calling the Method 1
        traverseString(str);
    }
}


Output

G e e k s f o r G e e k s 

Time Complexity: O(N)
Auxiliary Space: O(1)

Method 4: Using StringTokenizer

In this approach, we use StringTokenizer class in Java. It breaks a string into tokens based on the delimiter. Its usage is discouraged.

StringTokenizer(String str, String delim, boolean flag):
The first two parameters have same meaning.  The flag 
serves following purpose.

If the flag is false, delimiter characters serve to 
separate tokens. For example, if string is "hello geeks"
and delimiter is " ", then tokens are "hello" and "geeks".

If the flag is true, delimiter characters are 
considered to be tokens. For example, if string is "hello
 geeks" and delimiter is " ", then tokens are "hello", " " 
and "geeks".

Example 

Java




// Java Program to Iterate Over the Characters of a String
// Using StringTokenizer
 
// Importing required libraries
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Method 1
    // To traverse the string and
    // print the characters of the string
    static void traverseString(String str)
    {
        // If returnDelims is true, use the string itself as
        // a delimiter
        StringTokenizer st
            = new StringTokenizer(str, str, true);
 
        while (st.hasMoreTokens()) {
            System.out.print(st.nextToken() + " ");
        }
 
        System.out.println();
 
        // If returnDelims is false, use an empty string as
        // a delimiter
        st = new StringTokenizer(str, "", false);
 
        while (st.hasMoreTokens()) {
            System.out.print(st.nextToken() + " ");
        }
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "GeeksforGeeks";
 
        /// Calling the above Method1
        traverseString(str);
    }
}


Output

G e e k s f o r G e e k s 
GeeksforGeeks 

Time Complexity: O(N)
Auxiliary Space: O(N)

Method 5: Using String.split() method

In this approach, we use the split() method of the String class. It splits the string into substrings based on the regular expression provided.

Example 

Java




// Java Program to Iterate Over the Characters of a String
// Using String.split() method
 
// Importing required classes from respective packages
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Method 1
    // To traverse the string and
    // print the characters of the string
    static void traverseString(String str)
    {
        // Split str around matches of empty string ""
        String[] substrings = str.split("");
         
      for (String ch : substrings) {
            System.out.print(ch + " ");
        }
    }
   
    // Method 2
    // main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "GeeksforGeeks";
 
        // Calling the Method1 to
        // print the characters of the string
        traverseString(str);
    }
}


Output

G e e k s f o r G e e k s 

Time Complexity: O(N)
Auxiliary Space: O(N)

Method 6: Using Guava Library

In this approach, we use Lists.charactersOf(str) method which returns a view of an immutable list of characters.

Example 

Java




// Java Program to Iterate Over the Characters of a String
// Using Guava Library
 
// Importing required classes from respective packages
import com.google.common.collect.Lists;
import java.io.*;
 
// Main class
class GFG {
 
    // Method 1
    // To traverse the string and
    // print the characters of the string
    static void traverseString(String str)
    {
        // Using enhanced for loop
        for (Character ch : Lists.charactersOf(str)) {
            System.out.print(ch + " ");
        }
 
        // A new line is required
        System.out.println();
 
        // Using listIterator on the List
        // List<Characters>
        // iterator()
        // lambda
        Lists.charactersOf(str)
            .listIterator()
            .forEachRemaining(
                ch -> System.out.print(ch + " "));
 
        // A new line is required
        System.out.println();
 
        // Using method reference with listIterator
        // List<Characters>
        // iterator()
        Lists.charactersOf(str)
            .listIterator()
            .forEachRemaining(System.out::print);
    }
   
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "GeeksforGeeks";
 
        // Calling the Method1 to
        // print the characters of the string
        traverseString(str);
    }
}


Output

G e e k s f o r G e e k s 
G e e k s f o r G e e k s 
GeeksforGeeks

Time Complexity: O(N)
Auxiliary Space: O(N)

Method 7: Using String.chars() method

In this approach, we use the chars() method of the String class. This method does not return the Stream<Character> object due to performance reasons. It returns an IntStream(stream of integers) object which can be converted to a Stream<Character>(stream of characters).

Example 

Java




// Java Program to Iterate Over the Characters of a String
// Using String.chars() method
 
// Importing classes from required packages
import com.google.common.collect.Lists;
import java.io.*;
 
// main class
class GFG {
 
    // Method 1
    // to traverse the string and
    // print the characters of the string
    static void traverseString(String str)
    {
        // Display message for better readability
        System.out.println(
            "Auto boxing into Stream<Character>");
 
        // Using method reference
        str.chars()
            .mapToObj(Character::toChars)
            .forEach(System.out::print);
 
        str.chars().forEach(System.out::print);
 
        // A new line is required
        System.out.println();
 
        // Using lambda expressions by casting int to char
        str.chars()
            .mapToObj(i -> Character.valueOf((char)i))
            .forEach(System.out::print);
 
        // A new line is required
        System.out.println();
 
        str.chars()
            .mapToObj(i -> (char)i)
            .forEach(System.out::print);
 
        // A new line is required
        System.out.println();
        str.chars()
            .mapToObj(
                i -> new StringBuilder().appendCodePoint(i))
            .forEach(System.out::print);
 
        // A new line is required
        System.out.println();
 
        // Display message for better readability
        System.out.println(
            "Without boxing into Stream<Character>");
 
        str.chars().forEach(
            i -> System.out.print(Character.toChars(i)));
 
        // A new line is required
        System.out.println();
 
        str.chars().forEach(i -> System.out.print((char)i));
 
        // A new line is required for
        // readability in output clearly
        System.out.println();
 
        str.chars().forEach(
            i
            -> System.out.print(
                new StringBuilder().appendCodePoint(i)));
    }
 
    // Method 2
    // main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "GeeksforGeeks";
 
        // Calling the Method 1 to
        // print the characters of the string
        traverseString(str);
    }
}


Output

Auto boxing into Stream<Character>
GeeksforGeeks7110110110711510211111471101101107115
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
Without boxing into Stream<Character>
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

Time Complexity: O(N)
Auxiliary Space: O(N)

Method 8: Using Code Points

In this approach, we use String.codePoints() method which returns a stream of Unicode values.

Example

Java




// Java Program to Iterate Over the Characters of a String
// Using Code Points
 
// importing classes from respective packages
import com.google.common.collect.Lists;
import java.io.*;
 
// main class
class GFG {
 
    // Method 1
    // To traverse the string and
    // print the characters of the string
    static void traverseString(String str)
    {
        // Display message for better readability
        System.out.println(
            "Auto boxing into Stream<Character>");
       
        // Using method reference
        str.codePoints()
            .mapToObj(Character::toChars)
            .forEach(System.out::print);
        str.codePoints().forEach(System.out::print);
         
        // New line is required
        System.out.println();
       
        // Using lambda expressions by casting int to char
        str.codePoints()
            .mapToObj(i -> Character.valueOf((char)i))
            .forEach(System.out::print);
 
        // New line is required
        System.out.println();
 
        // now using the codepoints() over the string
        str.codePoints()
            .mapToObj(i -> (char)i)
            .forEach(System.out::print);
 
        // New line is required
        System.out.println();
       
        str.codePoints()
            .mapToObj(
                i -> new StringBuilder().appendCodePoint(i))
            .forEach(System.out::print);
 
       
        System.out.println();
       
      // Display message for readability in output
      System.out.println(
            "Without boxing into Stream<Character>");
        str.codePoints().forEach(
            i -> System.out.print(Character.toChars(i)));
 
        System.out.println();
         
      str.codePoints().forEach(
            i -> System.out.print((char)i));
 
        System.out.println();
         
      str.codePoints().forEach(
            i
            -> System.out.print(
                new StringBuilder().appendCodePoint(i)));
    }
   
    // Method 2
    // main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "GeeksforGeeks";
 
       // Calling the Method1 to 
       // print the characters of the string
        traverseString(str);
    }
}


Output

Auto boxing into Stream<Character>
GeeksforGeeks7110110110711510211111471101101107115
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks
Without boxing into Stream<Character>
GeeksforGeeks
GeeksforGeeks
GeeksforGeeks

Time Complexity: O(N)
Auxiliary Space: O(N)



Similar Reads

Java Program to Iterate Over Characters in String
Given string str of length N, the task is to traverse the string and print all the characters of the given string using java. Illustration: Input : str = “GeeksforGeeks” Output : G e e k s f o r G e e k sInput : str = "GfG" Output : G f G Methods: Using for loops(Naive approach)Using iterators (Optimal approach) Method 1: Using for loops The simple
3 min read
Program to Iterate over a Stream with Indices in Java 8
Given a Stream in Java, the task is to iterate over it with the help of indices. Examples: Input: Stream = [G, e, e, k, s] Output: [0 -> G, 1 -> e, 2 -> e, 3 -> k, 4 -> s] Input: Stream = [G, e, e, k, s, F, o, r, G, e, e, k, s] Output: [0 -> G, 1 -> e, 2 -> e, 3 -> k, 4 -> s, 5 -> F, 6 -> o, 7 -> r, 8 -> G, 9 -> e, 10 -> e, 11 -> k, 12 -> s] Method
2 min read
How to iterate over a TreeMap in Java?
Given a TreeMap, the task is to iterate this TreeMap in Java. The TreeMap in Java is used to implement Map interface and NavigableMap along with the Abstract Class. We cannot iterate a TreeMap directly using iterators, because TreeMap is not a Collection. So we will have to use TreeMap.entrySet() method. This method returns a collection-view(Set
3 min read
How to iterate over a 2D list (list of lists) in Java
Given a 2D list, the task is to iterate this 2D list in Java. 2D list (list of lists) The 2D list refers to a list of lists, i.e. each row of the list is another list. [ [5, 10], [1], [20, 30, 40] ] Iterate a 2D list: There are two ways of iterating over a list of list in Java. Iterating over the list of lists using loop: Get the 2D list to the ite
4 min read
Java Program to Iterate Over Arrays Using for and foreach Loop
An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++. Here, we have explained the for loop and foreach loop to display the elements of an array in Java. 1. For Loop:For-loop provides a concise way of writing the loop structure. A for statement consumes the initializ
4 min read
Iterate Over Vector Elements in Java
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number of elements in it as there is no size limit. We can iterate over vector by the following ways: Simple for-loopEnhanced for-loopIteratorsEnumeration interface Method 1: Simple for-loop The idea is to run a for loop from start till the size of the
4 min read
Iterate Over Unmodifiable Collection in Java
The Collection is a framework that provides an architecture to store and manipulate the group of objects. In Java Collections, we perform operations like searching, sorting, Iterating over the given set of elements. Modifiable: Modifiable means we can perform operations like adding, deleting, updating elements in collection data structures. Example
3 min read
How to Iterate over a Queue in Java?
Queue is a concept of Linear Data Structure that follows the concept of FIFO(First In First Out). Queues are majorly used to maintain the order of the elements to which they are added. In this article, we will learn to perform Queue Iteration in Java. Queue Iteration Program in JavaSyntax with ExamplesIterator<String> it = queue.iterator();wh
1 min read
How to Iterate Over a HashSet Without an Iterator in Java?
In Java, we can iterate over a HashSet without using an Iterator. For this, we need two methods. We can directly loop through the elements of the HashSet. In this article, we will discuss the two methods to iterate over a HashSet without using Iterator. Program to Iterate over a HashSet without an Iterator1. Using For-Each loopSyntax: for (Datatype
2 min read
How to Iterate Over the Elements in a TreeSet in Natural Order in Java?
In Java, to iterate over the elements of a TreeSet in their Natural Order, one must either use a custom comparator provided or traverse the elements in ascending order based on their natural ordering. A TreeSet in Java keeps up with its components in arranged requests. In this article, we will learn how to iterate over the elements in a TreeSet in
2 min read
How to Iterate over the Elements of a PriorityQueue in Java?
In Java, a Priority Queue is a Data structure that allows the users to store data based on their priority so that the elements with the highest priority can be accessed in constant time. In this article, we will learn how to iterate over the elements of a PriorityQueue in Java. Example Input: PriorityQueue pq ={1,2,3,4,5}Output: Elements of pq: 1 2
2 min read
How to Iterate LinkedList in Java?
LinkedList in java is basically a part of the collection framework present in java.util package. It is the implementation of the LinkedList data structure that stores elements in a non-contiguous manner inside the memory. Five ways to iterate a LinkedList are: Using for loopUsing while loopUsing enhanced for loopUsing IteratorUsing forEach() method
5 min read
Stream iterate(T,Predicate,UnaryOperator) method in Java with examples
The iterate(T, java.util.function.Predicate, java.util.function.UnaryOperator) method allows us to iterate stream elements till the specified condition. This method returns a sequential ordered Stream produced by iterative application of the given next function to an initial element, conditioned on satisfying hasNext predicate passed as parameter.
2 min read
How to Iterate HashMap in Java?
HashMap is a part of Java’s collection providing the basic implementation of the Map interface of Java by storing the data in (Key, Value) pairs to access them by an index of another type. One object is listed as a key (index) to another object (value). If you try to insert the duplicate key, it will replace the element of the corresponding key. In
5 min read
How to Iterate LinkedHashMap in Reverse Order in Java?
The LinkedHashMap is used to maintain an order of elements inserted into it. It provides where the elements can be accessed in their insertion order. A LinkedHashMap contains values based on the key. It implements the Map interface and extends the HashMap class. It contains only unique elements or mappings. Syntax of Linkedhashmap public class Link
6 min read
Java Program to Iterate Vector using Enumeration
The Vector class implements a growable array of objects. It is available in java.util package. It implements the List interface. The Enumeration interface defines the methods by which you can traverse the elements in a collection of objects. Now in order to add elements Vector Syntax: public class Vector<E> extends AbstractList<E> imple
2 min read
Java Program to Iterate LinkedHashSet Elements
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. When cyc
3 min read
Iterate List in Reverse Order in Java
The List interface provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. Example Input: ["geeks", "for", "Geeks"] Output: ["Geeks", "for", "
3 min read
Iterate TreeMap in Reverse Order in Java
The TreeMap in Java is used to implement the Map interface and NavigableMap along with the AbstractMap Class. The TreeMap is sorted according to the natural ordering of its keys. There are three simple ways to iterate TreeMap in reverse order in Java: Using the reverseOrder() methodUsing the descendingKeySet() methodUsing the descendingMap() method
3 min read
Iterate through LinkedHashMap using an Iterator in Java
LinkedHashMap is a pre-defined class in java like HashMap. The only difference between LinkedHashMap and HashMap is LinkedHashMap preserve insertion order while HashMap does not preserve insertion order. The task is to iterate through a LinkedHashMap using an Iterator. We use the Iterator object to iterate through a LinkedHashMap. Example Input: Ke
2 min read
Iterate Through Elements of LinkedHashSet in Java
The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. Example: Input: ["Geeks", "for", "Geeks"] Output: Geeks for Geeks Input: [9, 4, 6, 2, 8] Output: 9 4 6 2 8 Different Ways to Iterate LinkedHashSet Elements: Using the for
3 min read
How to Iterate through Collection Objects in Java?
Any group of individual objects which are represented as a single unit is known as the Collection of the objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2 which holds all the collection classes and interface in it. The Collection interface (java.util.Collection) and Map interface (java.util.Map) are
3 min read
How to iterate LinkedHashMap in Java?
LinkedHashMap class extends HashMap and maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating a LinkedHashMap, the elements will be returned in the order in which they were inserted. There are basically two ways to iterate over LinkedH
2 min read
Iterate a LinkedList in Reverse Order in Java
For traversing a linked list in reverse order we can use Descending Iterator or List Iterator 1. Descending Iterator Syntax: LinkedList<String> linkedlist = new LinkedList<>(); Iterator<String> listIterator = linkedlist.descendingIterator(); Returns: Descending Iterator returns the Iterator that points to the end of the linked lis
2 min read
Iterate List in Java using Loops
In this article, we are going to see how to iterate through a List. In Java, a List is an interface of the Collection framework. List can be of various types such as ArrayList, Stack, LinkedList, and Vector. There are various ways to iterate through a java List but here we will only be discussing our traversal using loops only. So, there were stand
7 min read
How to Iterate the Vector Elements in the Reverse Order in Java?
The Vector class is found in java.util package and it implements List interface. The Vector class is included in the java collection framework from Java version 1.2. Unlike arrays, vectors can grow and shrink their size, and thus they are also called the Dynamic Array. Vectors are synchronized, ie they are thread-safe. There are basically two metho
3 min read
How to Iterate Through HashTable in Java?
HashTable is an underlying data structure where the insertion order in HashTable is not preserved, and it is based on the hashcode of keys. Duplicates keys are not allowed, but values can be duplicated. Heterogeneous objects are allowed for both keys and values. Value null is not allowed for both key and value otherwise we will get RunTimeException
8 min read
How to iterate any Map in Java
There are generally five ways of iterating over a Map in Java. In this article, we will discuss all of them and also look at their advantages and disadvantages.First of all, we cannot iterate a Map directly using iterators, because Map are not Collection. Also before going further, you must know a little-bit about Map.Entry<K, V> interface.Si
5 min read
Iterate through List in Java
Lists in Java allow us to maintain an ordered collection of objects. Duplicate elements as well as null elements can also be stored in a List in Java. The List interface is a part of java.util package and it inherits the Collection interface. It preserves the order of insertion. There are several ways to iterate over List in Java. They are discusse
8 min read
How to Iterate HashSet in Java?
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. It stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code. Methods to Iterate HashSet There are three simple ways to itera
3 min read
Practice Tags :