最近项目上经常要用到计算字符串的长度的问题,有时需要按照byte进行计算长度,所以我就想在页面上用js实现,于是就到网上查了相关的资料,发现确实有很多的版本,这里给出两个比较好用的. //方法一:逐个字符检查是否中文字符 String.prototype.getByteLen = function() { var len = 0; for (var i=0; i<this.length; i++) { if ((this.charCodeAt(i) & 0xff00) != 0) len +
http://www.qttc.net/201207136.html // UTF8字符集实际长度计算 function getStrLeng(str){ var realLength = 0; var len = str.length; var charCode = -1; for(var i = 0; i < len; i++){ charCode = str.charCodeAt(i); if (charCode >= 0 && charCode <= 128) {
话不多说,直接上代码........... public static void main(String[] args) { String str="I'm go to swimming"; Set<String> set=new HashSet<>(); for (int i = 0; i < str.length(); i++) { String s = str.substring(i, i+1); set.add(s); } Iterator<
jdk本身就自带获取字符串字节长度的api了,但字符串如果包含特殊符号或全半角符号或标点符号获取到的结果会有偏差,最好的证据就是新浪微博的字数统计了 // jdk自带的获取字节长度 //注意getBytes()默认获取的是以文件编码格式的bytes,通常都是UTF-8(可以看api),不同编码格式的bytes,获取到的长度也不同,本人亲自测试过,建议获取有指定编码格式的bytes长度,如:getBytes("UTF-8") int length = new String().getBy