Iterate Over the Characters of a String in Java

Java 8 furnishes us with another technique String.chars() which returns an IntStream. The returned IntStream contains a number of portrayals of the characters in the string. Here we get stream1 from myString.chars(). We map the returned IntStream into an item. The stream1.mapToObj() changes over the whole number qualities into their particular person same. Be that as it may, to show and peruse the characters, we want to change over them into an easy to understand character structure.

Iterate Over the Characters of a String in Java

Given string str of length N, the undertaking is to cross the string and print every one of the characters of the given string.

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

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 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 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)

1. Naive solution

public class TestJava {
  public static void main(String[] args) {
	String str = "w3spoint";
 
        // using simple for-loop
        for (int i = 0; i < str.length(); i++) {
            System.out.println(str.charAt(i));
        }
   }
}

2. Using String.toCharArray() method

public class TestJava {
  public static void main(String[] args) {
	String str = "w3spoint";
 
	// convert string to `char[]` array
        char[] chars = str.toCharArray();
 
        // iterate over `char[]` array using enhanced for-loop
        for (char ch: chars) {
            System.out.println(ch);
        }
  }
}

3. Using StringCharacterIterator

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
 
public class TestJava {
  public static void main(String[] args) {
	String str = "w3spoint";
 
	CharacterIterator it = new StringCharacterIterator(str);
 
        while (it.current() != CharacterIterator.DONE)
        {
            System.out.println(it.current());
            it.next();
        }
  }
}

4. Using StringTokenizer

import java.util.StringTokenizer;
 
public class TestJava {
  public static void main(String[] args) {
	String str = "w3spoint";
 
	@Deprecated
        // if returnDelims is true, use the string itself as a delimiter
        StringTokenizer st = new StringTokenizer(str, str, true);
 
        while (st.hasMoreTokens()) {
            System.out.println(st.nextToken());
        }
  }
}

5. Using String.Split() method

public class TestJava {
  public static void main(String[] args) {
	String str = "w3spoint";
 
	String[] arr = str.split("");
 
        for (String ch: arr) {
            System.out.println(ch);
        }
  }
}

6. Using String.chars() method

public class TestJava {
  public static void main(String[] args) {
	String str = "w3spoint";
 
	//1. Implicit boxing into `Stream<Character>`
 
        //1.1. Using method reference
        str.chars()
                .mapToObj(Character::toChars)
                .forEach(System.out::println);
 
        //1.2. Using lambda expressions by casting `int` to `char`
        str.chars()
                .mapToObj(i -> Character.valueOf((char) i))
                .forEach(System.out::println);
 
        str.chars()
                .mapToObj(i -> (char) i)
                .forEach(System.out::println);
 
        str.chars()
                .mapToObj(i -> new StringBuilder().appendCodePoint(i))
                .forEach(System.out::println);
 
        //2. Without boxing into `Stream<Character>`
 
        str.chars()
                .forEach(i -> System.out.println(Character.toChars(i)));
 
        str.chars()
                .forEach(i -> System.out.println((char) i));
 
        str.chars()
                .forEach(i -> System.out.println(new StringBuilder()
                        .appendCodePoint(i)));
  }
}

Also Read: Compare two Strings in Java

Leave a Reply

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