Loop through the characters of a String
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A loop over the indexes 0 to length() - 1 visits every character of a String. Inside the loop, charAt(i) gives the character for that round, so you can count it, check it or copy it.
Visit every character
How many times does a appear in a word? Look at each character in turn: for (int i = 0; i < s.length(); i++) visits every index once, and s.charAt(i) is the character for that round. A char is compared with == and single quotes.
Trace the code
Count the a in "papa"
Variables
- word
- papa
Output
(nothing printed yet)Line 3word holds 4 characters, so its indexes are 0 to 3.
s.length() instead of a.length, and s.charAt(i) instead of a[i].Ready-made checks: the Character class
To count the vowels in Aishwarya, both A and a must count. The Character class has ready-made helpers for one char: change its case, or ask whether it is a digit or a letter.
Example 1 · Count the vowels in a name
public class Vowels { public static void main(String[] args) { String name = "Aishwarya"; int count = 0; for (int i = 0; i < name.length(); i++) { char ch = Character.toLowerCase(name.charAt(i)); if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') { count++; } } System.out.println("Vowels in " + name + ": " + count); }}Vowels in Aishwarya: 4
What this code does
Character.toLowerCase()turnsAintoa, so one check covers capitals and small letters.- The vowels are A, i, a and a, so
countends at 4. nameitself is not changed; only thecharinchis made small.
Other helpers you will use often (each takes one char):
Character.isDigit(ch): is it 0 to 9?Character.isLetter(ch): is it a letter?Character.isUpperCase(ch)andCharacter.isLowerCase(ch)Character.toUpperCase(ch): the capital version ofch
ch == "a" does not compile (bad operand types): "a" is a String. A char takes single quotes, 'a'.for-each with toCharArray()
To check that a mobile number has only digits, you need each character but not its position. toCharArray() gives a char[] of all the characters, so a for-each loop (opens in a new tab) can read them.
Example 2 · Check a mobile number
public class MobileCheck { public static void main(String[] args) { String mobile = "98765x3210"; int digits = 0; for (char ch : mobile.toCharArray()) { if (Character.isDigit(ch)) { digits++; } } System.out.println("Digits: " + digits + " of " + mobile.length()); boolean ok = mobile.length() == 10 && digits == 10; System.out.println(ok ? "Valid mobile number" : "Invalid mobile number"); }}Digits: 9 of 10 Invalid mobile number
What this code does
- The for-each loop reads every
charof the array thattoCharArray()gives. - The
xis not a digit, so only 9 of the 10 characters count and the number is invalid.
Use for-each when you only read the characters. Use the index loop when you need the position, or want to go backwards.
Going backwards: reverse a word
Is madam the same read backwards? A palindrome reads the same both ways. Loop from the last index down to 0 and add each character to a new String.
Example 3 · Reverse a word and check for a palindrome
public class Palindrome { public static void main(String[] args) { String word = "madam"; String rev = ""; for (int i = word.length() - 1; i >= 0; i--) { rev = rev + word.charAt(i); } System.out.println("Reverse: " + rev); if (word.equals(rev)) { System.out.println(word + " is a palindrome"); } else { System.out.println(word + " is not a palindrome"); } }}Reverse: madam madam is a palindrome
What this code does
- The loop starts at the last index,
word.length() - 1, and goes down to 0. revstarts empty, sorev + word.charAt(i)adds each character as text.- The texts are compared with
equals(), as in Compare Strings (opens in a new tab).
rev = rev + ch makes a new String every round, which is fine for a short word. For long text, StringBuilder (opens in a new tab) builds it faster and has a ready reverse().
Next step
Check your understanding
9 quick questions