How to Parse an Input String to Count Letters in Java
The string data type in Java is like an array of characters, and you can use the "length" method to determine the number of characters in a string input by the user. Counting the letters in such a string is slightly more difficult, since characters such as spaces, numbers, and punctuation in the array must be discounted. Combine the "isLetter" method of the character class with a "for" loop to parse through an input string and count the letters in it.
Instructions
-
-
1
Create a variable to hold the number of letters in the string:
int letters = 0;
Increment this variable each time a letter is encountered.
-
2
Declare a "for" loop to iterate through the string character by character:
for (int i=0;i<input.length();i++) {
The input string is assumed to be stored in a variable called "input." Change that name in the "for" loop if necessary.
-
-
3
Check the string on each iteration of the "for" loop, incrementing "letters" if a letter is encountered:
if (Character.isLetter(input.charAt(i))){letters++;}
Close the "for" loop with the "}" symbol. When the "for" loop is finished, "letters" contains the number of letters in the string.
-
1