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 s
Input : str = "GfG"
Output : G f G
Methods:
- Using for loops(Naive approach)
- Using iterators (Optimal approach)
Method 1: Using for loops
The simplest or rather we can say naive approach to solve this problem is to iterate using a for loop by using the variable ‘i’ till the length of the string and then print the value of each character that is present in the string.
Example
Java
class GFG {
static void getChar(String str)
{
for ( int i = 0 ; i < str.length(); i++) {
System.out.print(str.charAt(i));
System.out.print( " " );
}
}
public static void main(String[] args)
{
String str = "GeeksforGeeks" ;
getChar(str);
}
}
|
Output
G e e k s f o r G e e k s
Time complexity is O(N) and space complexity is O(1)
Method 2: Using iterators
The string can be traversed using an iterator. We would be importing CharacterIterator and StringCharacterIterator classes from java.text package
Example:
Java
import java.io.*;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
class GFG {
static void getChar(String str)
{
CharacterIterator itr
= new StringCharacterIterator(str);
while (itr.current() != CharacterIterator.DONE) {
System.out.print(itr.current());
System.out.print( " " );
itr.next();
}
}
public static void main(String[] args)
{
String str = "GfG" ;
getChar(str);
}
}
|
Time Complexity: O(N) and space complexity is of order O(1)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!