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.
Input : str = “GeeksforGeeks” Output : G e e k s f o r G e e k s
Input : str = "GfG" Output : G f G
- 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.
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
G f G
Time Complexity: O(N) and space complexity is of order O(1)