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)
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.