我这里要做一个输入的判断,汉字、英文和数字我都能识别出,特殊字符里面分有中文和英文的,不知道怎么区别,各位有没有什么方法解决?
8 回答
慕无忌1623718
TA贡献1744条经验 获得超4个赞
这个方法检测特殊字符:
Pattern p = Pattern.compile("[&%$#@!()*^]"); //<---- you can add more characters to check here
Matcher m = p.matcher(myEditText2);
if (m.find()) {
editText.setError("you can not enter special Character");
return false;
}导入包:
import java.util.regex.Matcher; import java.util.regex.Pattern;
慕容708150
TA贡献1831条经验 获得超4个赞
char[] myChar = s.toCharArray();
for (int i = 0; i < myChar.length; i++) {
if ((char) (byte) myChar[i] != myChar[i]) {
//中文相关字符
}
}试一下这个看看可以么
String str = "我爱你,xr.";
char[] array = str.toCharArray();
int chineseCount = 0;
int englishCount = 0;
for (int i = 0; i < array.length; i++) {
if((char)(byte)array[i]!=array[i]){
chineseCount++;
}else{
englishCount++;
}
}
这个是加入计数后的代码 可以计算中文字符和英文字符个数 其中中文字符包含汉子 英文字符包含字母
料青山看我应如是
TA贡献1772条经验 获得超8个赞
String s="你";
if(String.valueOf(s.charAt(0)).getBytes().length==2){
System.out.println("是中文");
}else{
System.out.println("不是中文");
}
FFIVE
TA贡献1797条经验 获得超6个赞
String ss = "你";
Pattern pattern=Pattern.compile("[\u4e00-\u9fa5]");
Matcher matcher=pattern.matcher(ss);用正则
matcher为true是中文
慕田峪4524236
TA贡献1875条经验 获得超5个赞
public static String distinguish(String src) {
String result = "";
Pattern p;
Matcher m;
p = Pattern.compile("[\u4e00-\u9fa5]");
m = p.matcher(src);
if (m.find()) {
result = result + "有汉字 ";
}
p = Pattern.compile("[a-zA-Z]");
m = p.matcher(src);
if (m.find()) {
result = result + "有字母 ";
}
p = Pattern.compile("[0-9]");
m = p.matcher(src);
if (m.find()) {
result = result + "有数字 ";
}
p = Pattern.compile("\\p{Punct}");
m = p.matcher(src);
if (m.find()) {
result = result + "有标点符号 ";
}
return result;
}添加回答
举报
0/150
提交
取消
