Iterate over characters of a String in Java

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)));
  }
}
Please Share