如何判断java中char是中文字符还是英文字符
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何判断java中char是中文字符还是英文字符相关的知识,希望对你有一定的参考价值。
也就是java在文件操作读取字符数据时,read方法读取字符时怎么知道读两个字节(汉字)还是读一个字节(英文字符)?另外char是两个字节,所以在存储英文字符时高位全是零吗?
Java文件流有字符流和字节流两种,分别对应char和byte类型如果是字符流的read,一次读取两个字节,也就是一个char,需要注意的是Java采用Unicode编码,无论中文还是西文只要是char类型都是2字节。英文字符在Unicode以asc码存储,高位应该是0.使用这种方法需注意若字节为奇数则可能出错。
如果是字节流,一次性读1个字节,适用于任何场景,尤其是图片等二进制文件的读取,缺点是对文本文件识别率不高 参考技术A java中使用Unicode字符,所有字符均以2个字节存储,
编码呢,前256个和ASCII 编码一致,汉字字符编码应该在20000以上
也就说英文字符还是在大写字母 65-90 ,小写字母97-122 ,
但全角的英文字符编码在65313和65338之间
存储普通英文字符时高位全是零,但全角的不是本回答被提问者和网友采纳 参考技术B so easy
中文正则表达式
String regex = "[\\\\u4e00-\\\\u9fa5]";
java中判断一个字符串是否数字
String str = "123abc";if (!"".equals(str))
char num[] = str.toCharArray();//把字符串转换为字符数组
StringBuffer title = new StringBuffer();//使用StringBuffer类,把非数字放到title中
StringBuffer hire = new StringBuffer();//把数字放到hire中
for (int i = 0; i < num.length; i++)
// 判断输入的数字是否为数字还是字符
if (Character.isDigit(num[i])) 把字符串转换为字符,再调用Character.isDigit(char)方法判断是否是数字,是返回True,否则False
hire.append(num[i]);// 如果输入的是数字,把它赋给hire
else
title.append(num[i]);// 如果输入的是字符,把它赋给title
参考技术A ava中判断字符串是否为数字的方法:
1.用JAVA自带的函数
public static boolean isNumeric(String str)
for (int i = 0; i < str.length(); i++)
System.out.println(str.charAt(i));
if (!Character.isDigit(str.charAt(i)))
return false;
return true;
2.用正则表达式
首先要import java.util.regex.Pattern 和 java.util.regex.Matcher
public boolean isNumeric(String str)
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if( !isNum.matches() )
return false;
return true;
3.使用org.apache.commons.lang
org.apache.commons.lang.StringUtils;
boolean isNunicodeDigits=StringUtils.isNumeric("aaa123456789");
http://jakarta.apache.org/commons/lang/api-release/index.html下面的解释:
isNumeric
public static boolean isNumeric(String str)Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false.
null will return false. An empty String ("") will return true.
StringUtils.isNumeric(null) = false
StringUtils.isNumeric("") = true
StringUtils.isNumeric(" ") = false
StringUtils.isNumeric("123") = true
StringUtils.isNumeric("12 3") = false
StringUtils.isNumeric("ab2c") = false
StringUtils.isNumeric("12-3") = false
StringUtils.isNumeric("12.3") = false
Parameters:
str - the String to check, may be null
Returns:
true if only contains digits, and is non-null
上面三种方式中,第二种方式比较灵活。
第一、三种方式只能校验不含负号“-”的数字,即输入一个负数-199,输出结果将是false;
而第二方式则可以通过修改正则表达式实现校验负数,将正则表达式修改为“^-?[0-9]+”即可,修改为“-?[0-9]+.?[0-9]+”即可匹配所有数字。
以上是关于如何判断java中char是中文字符还是英文字符的主要内容,如果未能解决你的问题,请参考以下文章