接口:
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);
}
}