判断字符串中的英文字母汉字空格和其他字符个数

本文介绍了一个Java程序,该程序能够判断输入的字符串中包含的汉字、英文字母、数字及空格的数量,并计算出非汉字字母数字空格的个数。

接口:

package algorithm.sort.dao;


public interface CharacterJudgment {
/*判断字符串是不是汉字*/
public int isChinese(String con);
/* 判断是不是中文或英文字母*/
public int conValidate(String con);
/* 判断字符串是不是数字*/
public int isNumeric(String str);
/*判断空格*/
public int  spaceCharacter(String str);

}

实现类:

package algorithm.sort.imp;


import java.util.regex.Matcher;
import java.util.regex.Pattern;


import algorithm.sort.dao.CharacterJudgment;


public class CharacterJudgmentImp implements CharacterJudgment{
@Override
public int isChinese(String str) {


int count = 0;  
       Pattern p = Pattern.compile("[\\u4e00-\\u9fa5]");  
       Matcher m = p.matcher(str);  
       while(m.find()){  
           count++;  
       }  
       return count;  
   }  



/* 判断是不是中文或英文字母*/
@Override
public int conValidate(String str) {
int count = 0;  
        Pattern p = Pattern.compile("[a-zA-Z]");  
        Matcher m = p.matcher(str);  
        while(m.find()){  
            count++;  
        }  
        return count;  
}




/* 判断字符串是不是数字*/
@Override
public int isNumeric(String str) {


int count = 0;  
// Pattern pattern = Pattern.compile("[0-9]*");
       Pattern p = Pattern.compile("\\d");  
       Matcher m = p.matcher(str);  
       while(m.find()){  
           count++;  
       }  
       return count; 

}




/*判断空格的个数*/
@Override
public int spaceCharacter(String str) {
int count = 0;
if(null==str){
 count ++;
}else{
for(int i=0;i<str.length();i++){
char tmp = str.charAt(i);
if(tmp ==' '){
count++;
}
}
}
return count;
}

}

测试类:



package test;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;


import algorithm.sort.dao.CharacterJudgment;
import algorithm.sort.imp.CharacterJudgmentImp;


public class Test3 {


/**
* @param args
* @throws IOException 
*/
public static void main(String[] args) throws IOException {
CharacterJudgment  chajud = new CharacterJudgmentImp();
//Scanner sc = new Scanner(System.in);
//String con =" 有你的世界真好 LOVE 5201314 ";
System.out.println("请输入字符串:");
//String con = sc.nextLine();
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
String con = br.readLine();
System.out.println("您输入的字符串是:"+con);
int count=chajud.isChinese(con);
int count1 = chajud.conValidate(con);
int count2 = chajud.isNumeric(con);
int count3 = chajud.spaceCharacter(con);
//非汉字 字母 数字 空格 的个数
int all = con.length();
int count4=0;
count4 = all-count-count1-count2-count3;
System.out.println("汉字个数为:"+count);
System.out.println("英文字母个数为:"+count1);
System.out.println("数字个数为:"+count2);
System.out.println("空格的个数为:"+count3);
System.out.println("其他字符个数为:"+count4);

}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值