CodeHub Menu
Home Exercise Practice About Download Portfolio Play Games NEW Privacy Policy Terms Contact
Login / Register

the number of digits, alphabets and special characters in the string

JAVA November 19, 2025 5 views 0 likes
Define a class to accept a String and print the number of digits, alphabets and special characters in the string.

Example:
S = "KAPILDEV@83"
Output:
Number of digits – 2
Number of Alphabets – 8
Number of Special characters – 1

Answer



Count Alphabets, Digits & Special Characters in Java

Java Program to Count Alphabets, Digits & Special Characters


import java.util.Scanner;

public class KboatCount
{
   public static void main(String args[]) 
   {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a string:");
        String str = in.nextLine();
             
        int len = str.length();

        int ac = 0;
        int sc = 0;
        int dc = 0;
        char ch;

        for (int i = 0; i < len; i++) {
            ch = str.charAt(i);
            if (Character.isLetter(ch))  
                ac++;    
            else if (Character.isDigit(ch))
                dc++;
            else if (!Character.isWhitespace(ch))
                sc++;
        }
        
        System.out.println("No. of Digits = " + dc);
        System.out.println("No. of Alphabets = " + ac);
        System.out.println("No. of Special Characters = " + sc);
        
    }
}
5 views 0 likes
Total visits: 2,089 • Unique visitors: 1,285