您的位置:首页 > 编程语言 > Java开发

【java】字符串中各种类型的字符串统计

2013-06-28 09:34 337 查看
package com.taylor.test;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Ei {

    public static void main(String[] args) {

        String s = "你好123 4Aa Zz-+&^%";

        Ei e = new Ei();

        System.out.println(e.getCharCount(s));

        System.out.println(e.getIntCount(s));

        System.out.println(e.getSpaceCount(s));

        System.out.println(e.getOtherCount(s));

    }

    //中英文字符

    private int getCharCount(String s){

        Pattern pat = Pattern.compile("[\u4E00-\u9FA5A-Za-z]",

                Pattern.CASE_INSENSITIVE);

        int i = 0;

        Matcher mat = pat.matcher(s);

        while (mat.find()) {

            i++;

        }

        return i;

    }

    //数字

    private int getIntCount(String s){

        Pattern pat = Pattern.compile("[0-9]",

                Pattern.CASE_INSENSITIVE);

        int i = 0;

        Matcher mat = pat.matcher(s);

        while (mat.find()) {

            i++;

        }

        return i;

    }

    //空格

    private int getSpaceCount(String s){

        Pattern pat = Pattern.compile("\\s",Pattern.CASE_INSENSITIVE);

        int i = 0;

        Matcher mat = pat.matcher(s);

        while (mat.find()) {

            i++;

        }

        return i;

    }

    //其他

    private int getOtherCount(String s){

        Pattern pat = Pattern.compile("[^\u4E00-\u9FA5A-Za-z0-9\\s]",

                Pattern.CASE_INSENSITIVE);

        int i = 0;

        Matcher mat = pat.matcher(s);

        while (mat.find()) {

            i++;

        }

        return i;

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: