Java counts the letters Spaces Numbers and others of input characters

  • 2020-06-12 09:02:58
  • OfStack

Enter 1 line of characters and count the number of letters, Spaces, Numbers and other characters.

Program analysis: using while statement, the condition is that the input character is not '\n '.

Program design:


import java.util.Scanner;
public class ex7 {
   public static void main(String args[])
   {
     System.out.println(" Please enter the string: ");
     Scanner scan=new Scanner(System.in);
     String str=scan.next();
     String E1="[\u4e00-\u9fa5]";
     String E2="[a-zA-Z]";
     int countH=0;
     int countE=0;
     char[] arrChar=str.toCharArray();
     String[] arrStr=new String[arrChar.length];
     for (int i=0;i<arrChar.length ;i++ )
     {
        arrStr[i]=String.valueOf(arrChar[i]);
     }
     for (String i: arrStr )
     {
        if (i.matches(E1))
        {
          countH++;
        }
        if (i.matches(E2))
        {
          countE++;
        }
     }
     System.out.println(" Number of Chinese characters "+countH);
     System.out.println(" Number of letters "+countE);
   }
} 

Related articles: