package com.example.phone.controller; public class test9 { public static void main(String[] args) { int result=0; String str="我爱中国aaa12333"; System.out.println(str.length()); //中文匹配正则 String mathcs = "[\u0391-\uFFE5]"; for (int i=0;i<str.length();i++){ // char temp=str.charAt(i);//不可以用这个 String temp=str.substring(i,i+1); if (temp.matches(mathcs)) { //说明匹配到的是中文的字符 result=result+2; }else { result=result+1; } } System.out.println(result); } }
因为java默认是使用Unicode编码,所以中文也是只是算一个,所以第一个得出的结果是12第二个就可以自己计算出字节的长度,因为一个中文占两个字节的,所以就计算出来是16;还有一种方法是使用ascall判断是否在0到255之间,不是的话说明是中文。匹配中文的正则是:[\u0391-\uFFE5]