Count Alphabets, Digits, Special Characters in String using Java

In this tutorial, we are going to learn java program to count the number of alphabets, digits, and special characters present in an input string from the user.

For any input string, we are going to print the number of alphabets (‘a’-‘z’ and ‘A’-‘Z’), the number of digits(0-9), and the number of special characters present.

For example

Case1: If the user inputs the string ‘%python123%$#’,

          the output should be, alphabets=5, digits=3, special characters=4.

Case2: If the user inputs the string ‘!!quescollll151!!%&’,

          the output should be, alphabets=10, digits=3, special characters=6.

Java Program to Count Alphabets, Digits, Special Characters in String

import java.util.*;
public class Main
{
    public static void main (String[]args)
    {
        int alphabet = 0, digit=0,symbol=0;
        System.out.println("Java program to count Alphabet, Digit, Symbols ");
        Scanner sc = new Scanner (System.in);
        System.out.println ("Please enter a String");
        String str = sc.nextLine(); 
        StringBuilder tempStr = new StringBuilder(str);
        for(int i = 0; i < str.length(); i++){
            if( (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') || (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z')) {        
                    alphabet++;
                }else if(str.charAt(i) >= '0' && str.charAt(i) <= '9'){
                digit++;
                }else{
                symbol++;
            }
        }
        System.out.println ("alphabet = "+alphabet+" Digit = "+ digit+" Symbol = "+symbol);
  }
}

Output

Java program to count Alphabet, Digit, Symbols 
Please enter a String
Qeusco123!@#
alphabet = 6 Digit = 3 Symbol = 3

Explanation

For the input string ‘Que123!@#scol89’, the alphabets used in this string are ‘Q’, ‘u’, ‘e’, ‘s’, ‘w’, ‘e’, ‘l’. The digits used in this string are ‘1’, ‘2’, ‘3’, ‘1’, ‘8’, and ‘9’. And the special character used in this string is ‘!’, ‘@’, and ‘#’.

That makes the number of alphabet =7,

                    the number of digits = 5

                    the number of special characters =3