Saturday, July 8, 2023

Define a class to accept a string and print number of digits, alphabets and special characters in the string.

Define a class to accept a string and print number of digits, alphabets and special characters in the string.
Example: 
Input:     S = KAPILDEV@83
Output:  Number of Digits - 2
              Number of Alphabets - 8
              Number of Special Characters - 1




                 
Solution:

import java.util.Scanner;
public class Year2023Q1
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string:");
        String str = sc.nextLine();
        int len=str.length();
        int digitCount=0,letterCount=0,whitespaceCount=0,spclCharCount=0;
       
//      Method 1
        for(int i=0;i<len;i++)
        {
            char ch=str.charAt(i);
            if(ch>='0' && ch<='9')
                digitCount++;
            if(ch>='A' && ch<='Z'|| ch>='a' && ch<='z')
                letterCount++;
            if(ch==' ')
                whitespaceCount++;
            spclCharCount=len-(digitCount+letterCount+whitespaceCount);
        }
       
//      Method 2    
        for(int i=0;i<len;i++)
        {
            char ch=str.charAt(i);
            if(Character.isDigit(ch))
                digitCount=digitCount+1;
            if(Character.isLetter(ch))
                letterCount+=1;
            if(Character.isWhitespace(ch))
                whitespaceCount++;
            spclCharCount=len-(digitCount+letterCount+whitespaceCount);
        }
       
        System.out.println("Number of digits = "+digitCount);
        System.out.println("Number of letters = "+letterCount);
        System.out.println("Number of special Char = "+spclCharCount);
        System.out.println("Number of whitespace = "+whitespaceCount);  
    }
}

Output:


No comments:

Post a Comment

Check whether the word is Special word or Palindrome word.

Special words are those words which starts and ends with the same letter.  Examples: EXISTENCE COMIC WINDOW Palindrome words are those words...