➤ Sum of digits in a String
➤ Count No of Vowels String
➤ String Pattern Programs in Java
➤ Take String Input In Java
➤ Take Multiple String Input in Java
➤ How To Reverse a String In Java
➤ Remove Special Characters
➤ String – Remove Character
➤ String Palindrome In Java
➤ Sort String In Java
➤ How to Compare Strings In Java
➤ Second Occurrence of Character
➤ Replace nth Occurrence String
➤ Last Occurrence of Character
➤ Uppercase & Lowercase
➤ Java Check If Char is Uppercase
➤ Check If String is Uppercase
➤ Swap Characters in String Java
➤ Java String indexOf() Method
➤ How to Replace Dot in Java?
➤ How to Find Length of String
➤ Substring Method In Java
➤ Split Method In Java
How to iterate Through String Java? In this section, we will discuss how can you iterate through a string in Java. We will write a Java program to iterate through string Java and to iterate over the string we can use loops.
To achieve the task we have two ways:-
1) Using iterators
2) Using loops
Iterate Through Characters In a String Java
Let us see how to iterate through String In Java using for loop. Usually to iterate an array or string elements we use for loop. It keeps on looping until the condition is satisfied. To iterate over the string length we can use the charAt() method.
public class Main {
public static void main(String[] args) {
String string = "Java";
for (int i = 0; i < string.length(); i++) {
System.out.println(string.charAt(i));
}
}
}
Output:-
J
a
v
a
public class Main {
public static void main(String[] args) {
String string = "Java Programming";
for (int i = 0; i < string.length(); i++) {
System.out.print(string.charAt(i));
}
}
}
Output:-
Java Programming
Iterate through String Java using Iterators
Let us see how to iterate through characters in a string Java using iterators. See the below code.
The object that is used to loop through the collections like ArrayList, HashSet and more is called an iterator. we call it an iterator because the technical term for looping is iterate.
In the below code, we need to import CharacterIterator and StringCharacterIterator. The text is an interface that is used to get the character in the string. The StringCharacterIterator sets the index of the iterator to 0.
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class Main {
public static void main(String[] args) {
String string = "Java Programming";
CharacterIterator itrator = new StringCharacterIterator(string);
while (itrator.current() != CharacterIterator.DONE) {
System.out.print(itrator.current() + " ");
itrator.next();
}
}
}
Output:-
J a v a P r o g r a m m i n g
If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!