Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Program to Swap characters in a String
Next article icon

Iterate Over the Characters of a String in Java

Last Updated : 28 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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)



Next Article
Java Program to Swap characters in a String

G

Ganeshchowdharysadanala
Improve
Article Tags :
  • Java
  • Java Programs
  • Java-String-Programs
Practice Tags :
  • Java

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 (Opti
    3 min read
  • How to Shuffle Characters in a String in Java?
    In this article, we will learn how to shuffle characters in a String by using Java programming. For this, we have taken a String value as input and the method is available in java.util package and this method takes a list as input. Steps to shuffle characters in a String in JavaFirst, take one Strin
    2 min read
  • Java Program to Swap characters in a String
    The task at hand involves manipulating a string S of length N, given as input. The string is subjected to a series of B swaps, each performed according to the following procedure: The character at position i is swapped with the character located C positions ahead of it, or (i + C)%N. This swapping p
    6 min read
  • How to find the first and last character of a string in Java
    Given a string str, the task is to print the first and the last character of the string. Examples: Input: str = "GeeksForGeeks" Output: First: G Last: s Explanation: The first character of the given string is 'G' and the last character of given string is 's'. Input: str = "Java" Output: First: J Las
    3 min read
  • Remove first and last character of a string in Java
    Given a string str, the task is to write the Java Program to remove the first and the last character of the string and print the modified string. Examples: Input: str = "GeeksForGeeks"Output: "eeksForGeek"Explanation: The first and last characters of the given string are 'G' and 's' respectively. Af
    5 min read
  • Add index to characters and reverse the string
    Given a string str, the task is to encrypt and reverse the string. The string is encrypted by adding every character of the string with it's index in the string i.e. if character'a' is at index 2 then the character in the updated string will be 'a' + 2 = 'c'. Since value of string may go beyond 256,
    4 min read
  • Java Program to Separate the Individual Characters from a String
    The string is a sequence of characters including spaces. Objects of String are immutable in java, which means that once an object is created in a string, it's content cannot be changed. In this particular problem statement, we are given to separate each individual characters from the string provided
    2 min read
  • Convert a String to Character Array in Java
    Converting a string to a character array is a common operation in Java. We convert string to char array in Java mostly for string manipulation, iteration, or other processing of characters. In this article, we will learn various ways to convert a string into a character array in Java with examples.
    2 min read
  • Java program to print all duplicate characters in a string
    Given a string, the task is to write Java program to print all the duplicate characters with their frequency Example: Input: str = "geeksforgeeks" Output: s : 2 e : 4 g : 2 k : 2 Input: str = "java" Output: a : 2 Approach: The idea is to do hashing using HashMap. Create a hashMap of type {char, int}
    2 min read
  • Convert String to Stream of Chars in Java
    The StringReader class from the java.io package in Java can be used to convert a String to a character stream. When you need to read characters from a string as though it were an input stream, the StringReader class can be helpful in creating a character stream from a string. In this article, we wil
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences