get Chinese String Length - Java Internationalization

Java examples for Internationalization:Chinese

Description

get Chinese String Length

Demo Code


import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main{
    public static void main(String[] argv){
        String s = "java2s.com";
        System.out.println(getLength(s));
    }/*w w w  .  ja va2  s. co  m*/
    
    public static int getLength(String s) {
        if (StringUtil.isEmpty(s)) {
            return 0;
        }
        String chinese = "[\u4e00-\u9fa5]"; 
        String emoji = ""; //emoji??
        int strLength = 0;
        String[] sArray = s.split(""); 
        for (String string : sArray) { 
            if (StringUtil.isEmpty(string)) {
                continue;
            }
            if (string.matches(chinese)) {
                strLength += 2; 
            } else {
                strLength += 1; 
            }
        }
        return strLength;
    }
    public static boolean isEmpty(String str) {
        return str == null || "".equals(str.trim());
    }
}

Related Tutorials