get String By Length for Chinese - Android Internationalization

Android examples for Internationalization:Chinese

Description

get String By Length for Chinese

Demo Code


public class Main{

    public static String getStringByLength(String string, int length) {
        StringBuffer stringBuffer = new StringBuffer();

        int valueLength = 0;
        String chinese = "[\u4e00-\u9fa5]";

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

            String temp = string.substring(i, i + 1);
            if (temp.matches(chinese)) {
                if (valueLength >= (length - 1))
                    break;
                valueLength += 2;//from  w w w  . j ava  2s .co  m

            } else {
                if (valueLength >= length)
                    break;
                valueLength += 1;

            }
            stringBuffer.append(temp);
        }
        return stringBuffer.toString();
    }

}

Related Tutorials