获取字符串中汉字的个数

  • 实例说明

  字符串中可以包含数字、字母汉字或者其他字符。使用Character类的isDigit()方法可以判断字符串中的某个字符是否为数字,使用Character类的isLetter()方法可以判断字符串中的某个字符是否为字母。本实例将介绍一种方法来判断字符串中的某个字符是否为汉字,通过次方法计算汉字的数量。

  • 关键技术

  正则表达式的使用,Java中使用Pattern用于正则表达式的编译表示形式,该类提供的静态方法matches()可以执行正则表达式的匹配。 

  • 设计过程

  

public class E_75 {
    public static void main(String[] args) {
        String text  = "";
        int amount = 0;
        for(int i = 0;i <text.length();i++){
            String regex = "^[\u4E00-\u9FA5]{0,}$";
            boolean matches = Pattern.matches(regex,text.charAt(i)+"");
            if(matches){
                amount++;
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/cglib/p/10668811.html
今日推荐