码迷,mamicode.com
首页 > 编程语言 > 详细

Java 按字节计算字符串的长度

时间:2019-12-14 22:40:16      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:style   param   factor   统计   oid   lan   coding   ted   格式   

   在《从后向前截取指定长度的字符串》中介绍了如何截取字符串,本文介绍如何统计字符串的字节长度。
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;


public class GetLength {
    private static final Logger logger = LoggerFactory.getLogger(GetLength.class);


    // 编码方式
    private static final String ENCODE_UTF = "UTF-8";


    /**
     * 计算中英文字符串的字节长度 <br/>
     * 一个中文占3个字节
     *
     * @param str
     * @return int 字符串的字节长度
     */
    public static int getLength(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        try {
            return str.getBytes(ENCODE_UTF).length;
        } catch (UnsupportedEncodingException e) {
            logger.error("计算中英文字符串的字节长度失败,", e);
        }
        return 0;
    }




    /**
     * 计算中英文字符串的字节长度
     *
     * @param str
     * @return int
     */
    public static int getStrLength(String str) {
        if (str == null || str.length() == 0) {
            return 0;
        }
        int len = 0;
        for (int i = 0, j = str.length(); i < j; i++) {
            //UTF-8编码格式中文占三个字节,GBK编码格式 中文占两个字节 ;
            len += (str.charAt(i) > 255 ? 3 : 1);
        }
        return len;
    }


    public static void main(String[] args) {
        String str = "农业银行 3Wiener,支付密";
        System.out.println(getLength(str));
        System.out.println(getStrLength(str));
    }
    
}

 

 

Java 按字节计算字符串的长度

标签:style   param   factor   统计   oid   lan   coding   ted   格式   

原文地址:https://www.cnblogs.com/east7/p/12041053.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!