zoukankan      html  css  js  c++  java
  • 计算字符个数-正则表达式

    判断键盘输入的字符串各个字符个数

    package test;
    import java.util.*;
    public class test {
        public static int[] num(String sentence){
            int[] res=new int[4];
            for(int i=0;i<sentence.length();i++){
                char ch=sentence.charAt(i);
                if(ch<='Z'&&ch>='A'||ch<='z'&&ch>='a')
                    res[0]++;
                else if(ch==' ')
                    res[1]++;
                else if('1'<=ch&&'9'>=ch)
                    res[2]++;
                else
                    res[3]++;
            }
            return res;
        }
        public static void main(String arg[]){
            System.out.println("请输入一行内容,以回车符结尾");
            Scanner scan=new Scanner(System.in);
            String sentence=scan.nextLine();
            int[] result=num(sentence);
            System.out.print("该行包含的英文、空格、数字及其它字符的个数分别为:");
            System.out.print(result[0]+""+result[1]+""+result[2]+""+result[3]);
        }
    
    }

     或使用正则表达式判断

    package test;
    import java.util.*;
    public class test {
        public static int[] num(String sentence){
            int[] res=new int[4];
            for(int i=0;i<sentence.length();i++){
                char ch=sentence.charAt(i);
                if(String.valueOf(ch).matches("^[A-Za-z]+$"))//字母正则表达式
                    res[0]++;
                else if(ch==' ')
                    res[1]++;
                else if(String.valueOf(ch).matches("^[0-9]+$"))//数字正则表达式
                    res[2]++;
                else
                    res[3]++;
            }
            return res;
        }
        public static void main(String arg[]){
            System.out.println("请输入一行内容,以回车符结尾");
            Scanner scan=new Scanner(System.in);
            String sentence=scan.nextLine();
            int[] result=num(sentence);
            System.out.print("该行包含的英文、空格、数字及其它字符的个数分别为:");
            System.out.print(result[0]+""+result[1]+""+result[2]+""+result[3]);
        }
    
    }
  • 相关阅读:
    安全公司
    HTML5 Security Cheatsheet
    渗透1
    dos其他
    Ddos 类别
    python之控制条件if语句
    python编码规范(二)——空行,换行,缩进
    python编码规范(一)——空格的使用
    python入门基础
    网页模板的自定义
  • 原文地址:https://www.cnblogs.com/ljs-666/p/8030165.html
Copyright © 2011-2022 走看看