edittext 内容长度

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34115898/article/details/85340499
碰到一个需求,需要限制输入内容的长度,在Java中 汉字与英文字符长度是不同的。所以单纯的s.length()判断出来的长度是不准确的。
写了一个方法来计算字符串的长度:
public static double getLength(String s) {
    double valueLength = 0;
    String chinese = "[\u4e00-\u9fa5]";
    for (int i = 0; i < s.length(); i++) {
        // 获取一个字符
        String temp = s.substring(i, i + 1);
        // 判断是否为中文字符
        if (temp.matches(chinese)) {
            // 中文字符长度为1
            valueLength += 1;
        } else {
            // 其他字符长度为0.5
            valueLength += 0.5;
        }
    }
    //进位取整
    return Math.ceil(valueLength);
}

记录一下

猜你喜欢

转载自blog.csdn.net/qq_34115898/article/details/85340499