In this tutorial to Count Letters in a String in java, we will see two examples to count the number of letters present in a String in Java.
- The first one, where the String is already defined in a program.
- The second one, where the String is taken as input from the user
Both the program uses for loop and if statement to count the letters so if you do not know about them, click the link below.
1. Java Program to Count the Letters in a String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //count letters in a string public class CountLetters { public static void main(String []args) { String str = "ab5gh6d"; //given String int count = 0; System.out.println("Given String is: "+str); for (int i = 0; i < str.length(); i++) { if (Character.isLetter(str.charAt(i))) { count++; } } System.out.println("Number of Letters in a given string: "+count); } } |
Output:
Given String is: ab5gh6d
Number of Letters in a given string: 5
2. Java Program to Count the Letters in a String (user’s input)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | //count letters in a string (user inputs) import java.util.Scanner; public class CountLetters { public static void main(String []args) { String str; int count = 0; Scanner sc = new Scanner(System.in); //Get input String System.out.println("Enter a string: "); str = sc.nextLine(); System.out.println("Entered String is: "+str); for (int i = 0; i < str.length(); i++) { if (Character.isLetter(str.charAt(i))) { count++; } } System.out.println("Number of Letters Present in a String are: "+count); } } |
Output:
Enter a string: 45ab6gh
Entered String is: 45ab6gh
Number of Letters Present in a String are: 4