Iterate Over the Characters of a String in Java
Last Updated :
28 Feb, 2022
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:
- Using Naive Approach
- Using String.toCharArray() method
- Using CharacterIterator
- Using StringTokenizer
- Using String.split() method
- Using Guava Library
- Using String.chars() method
- 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
import java.io.*;
import java.util.*;
class GFG {
static void traverseString(String str)
{
for ( int i = 0 ; i < str.length(); i++) {
System.out.print(str.charAt(i) + " " );
}
}
public static void main(String[] args)
{
String str = "GeeksforGeeks" ;
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
import java.io.*;
import java.util.*;
class GFG {
static void traverseString(String str)
{
char [] ch = str.toCharArray();
for ( int i = 0 ; i < ch.length; i++) {
System.out.print(ch[i] + " " );
}
}
public static void main(String[] args)
{
String str = "GeeksforGeeks" ;
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
import java.io.*;
import java.text.*;
class GFG {
static void traverseString(String str)
{
CharacterIterator it
= new StringCharacterIterator(str);
while (it.current() != CharacterIterator.DONE) {
System.out.print(it.current() + " " );
it.next();
}
}
public static void main(String[] args)
{
String str = "GeeksforGeeks" ;
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
import java.io.*;
import java.util.*;
class GFG {
static void traverseString(String str)
{
StringTokenizer st
= new StringTokenizer(str, str, true );
while (st.hasMoreTokens()) {
System.out.print(st.nextToken() + " " );
}
System.out.println();
st = new StringTokenizer(str, "" , false );
while (st.hasMoreTokens()) {
System.out.print(st.nextToken() + " " );
}
}
public static void main(String[] args)
{
String str = "GeeksforGeeks" ;
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
import java.io.*;
import java.util.*;
class GFG {
static void traverseString(String str)
{
String[] substrings = str.split( "" );
for (String ch : substrings) {
System.out.print(ch + " " );
}
}
public static void main(String[] args)
{
String str = "GeeksforGeeks" ;
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
import com.google.common.collect.Lists;
import java.io.*;
class GFG {
static void traverseString(String str)
{
for (Character ch : Lists.charactersOf(str)) {
System.out.print(ch + " " );
}
System.out.println();
Lists.charactersOf(str)
.listIterator()
.forEachRemaining(
ch -> System.out.print(ch + " " ));
System.out.println();
Lists.charactersOf(str)
.listIterator()
.forEachRemaining(System.out::print);
}
public static void main(String[] args)
{
String str = "GeeksforGeeks" ;
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
import com.google.common.collect.Lists;
import java.io.*;
class GFG {
static void traverseString(String str)
{
System.out.println(
"Auto boxing into Stream<Character>" );
str.chars()
.mapToObj(Character::toChars)
.forEach(System.out::print);
str.chars().forEach(System.out::print);
System.out.println();
str.chars()
.mapToObj(i -> Character.valueOf(( char )i))
.forEach(System.out::print);
System.out.println();
str.chars()
.mapToObj(i -> ( char )i)
.forEach(System.out::print);
System.out.println();
str.chars()
.mapToObj(
i -> new StringBuilder().appendCodePoint(i))
.forEach(System.out::print);
System.out.println();
System.out.println(
"Without boxing into Stream<Character>" );
str.chars().forEach(
i -> System.out.print(Character.toChars(i)));
System.out.println();
str.chars().forEach(i -> System.out.print(( char )i));
System.out.println();
str.chars().forEach(
i
-> System.out.print(
new StringBuilder().appendCodePoint(i)));
}
public static void main(String[] args)
{
String str = "GeeksforGeeks" ;
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
import com.google.common.collect.Lists;
import java.io.*;
class GFG {
static void traverseString(String str)
{
System.out.println(
"Auto boxing into Stream<Character>" );
str.codePoints()
.mapToObj(Character::toChars)
.forEach(System.out::print);
str.codePoints().forEach(System.out::print);
System.out.println();
str.codePoints()
.mapToObj(i -> Character.valueOf(( char )i))
.forEach(System.out::print);
System.out.println();
str.codePoints()
.mapToObj(i -> ( char )i)
.forEach(System.out::print);
System.out.println();
str.codePoints()
.mapToObj(
i -> new StringBuilder().appendCodePoint(i))
.forEach(System.out::print);
System.out.println();
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)));
}
public static void main(String[] args)
{
String str = "GeeksforGeeks" ;
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)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...