java 中英文长度_Java--计算中英文长度的若干种方法

在项目开发中经常碰到到输入字符的校验,特别是中英文混合在一起的校验。而为了满足校验的需求,有时需要计算出中英文的长度。

本文将通过几种常用的方法实现长度的计算:

public class StringLengthTest {

private static long startTime;

public static void main(String[] args) {

String validateStr = "中英文校验abcde接口ii";

for (int i = 0; i < 10; i++) {

validateStr = validateStr + validateStr;

}

int bytesStrLength = getBytesStrLength(validateStr);

int chineseLength = getChineseLength(validateStr);

int regexpLength = getRegExpLength(validateStr);

System.out.println("length:" + validateStr.length());

System.out.println("getBytesLength:" + bytesStrLength

+ ",chineseLength:" + chineseLength + ",regexpLength:"

+ regexpLength);

}

/**

* 根据字符编码 字节数生成一个临时的字符串

*

* @param validateStr

* @return

*/

public static int getBytesStrLength(String validateStr) {

startTime = System.currentTimeMillis();

String tempStr = "";

try {

tempStr = new String(validateStr.getBytes("gb2312"), "iso-8859-1");

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

System.out.println("getBytesStrLength time:"

+ (System.currentTimeMillis() - startTime));

return tempStr.length();

}

/**

* 获取字符串的长度,如果有中文,则每个中文字符计为2位

*

* @param validateStr

* 指定的字符串

* @return 字符串的长度

*/

public static int getChineseLength(String validateStr) {

startTime = System.currentTimeMillis();

int valueLength = 0;

String chinese = "[\u0391-\uFFE5]";

/* 获取字段值的长度,如果含中文字符,则每个中文字符长度为2,否则为1 */

for (int i = 0; i < validateStr.length(); i++) {

/* 获取一个字符 */

String temp = validateStr.substring(i, i + 1);

/* 判断是否为中文字符 */

if (temp.matches(chinese)) {

/* 中文字符长度为2 */

valueLength += 2;

} else {

/* 其他字符长度为1 */

valueLength += 1;

}

}

System.out.println("getChineseLength time:"

+ (System.currentTimeMillis() - startTime));

return valueLength;

}

/**

* 利用正则表达式将每个中文字符转换为"**" 匹配中文字符的正则表达式: [\u4e00-\u9fa5]

* 匹配双字节字符(包括汉字在内):[^\x00-\xff]

*

* @param validateStr

* @return

*/

public static int getRegExpLength(String validateStr) {

startTime = System.currentTimeMillis();

// String temp = validateStr.replaceAll("[\u4e00-\u9fa5]", "**");

String temp = validateStr.replaceAll("[^\\x00-\\xff]", "**");

System.out.println("getRegExpLength time:"

+ (System.currentTimeMillis() - startTime));

return temp.length();

}

}

结果:

getBytesStrLength time:2

getChineseLength time:30

getRegExpLength time:11

length:14336

getBytesLength:21504,chineseLength:21504,regexpLength:21504

建议:

使用 方式三:利用正则表达式 方式

方式一:根据字符编码 字节数生成一个临时的字符串(需要确定字符编码,不同编码结果长度不同)

方式二:获取字符串的长度,如果有中文,则每个中文字符计为2位(比较耗时)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值