String test = "123测试abc";
System.out.println(test.length);
此时会输出8,我想问一下如何可以自动把中文字转为2长度的..因为在数据库里面存储的话他就要占2的长度.谢了~~

解决方案 »

  1.   

    MySQL 的 varchar 是按 Unicode 字符来算的,varchar(10) 表示不管汉字、数字还是字母,都只能放 10 个
    Oracle 中 varchar2(10 byte) 汉字是按 2 个算的,varchar2(10 char) 汉字是按 1 个算的,nvarchar2(10) 汉字也是按 1 个算的
    MS SQL Server 中的 varchar(10) 的话汉字是按 2 个算的根据不同的数据库和字段类型长度,作不同的区别。
      

  2.   

    另外汉字并不一定是占两个字节!在 GB2312、GBK、GB18030 编码中是占两个字节,但是在 UTF-8 编码中至少占用三个字节!public class Test {    public static void main(String[] args) {
            String test = "123测试abc";
            System.out.println(gbkByteLength(test));
        }    public static int gbkByteLength(String str) {
            if (str == null) {
                throw new IllegalArgumentException("str is null");
            }
            if (str.length() == 0) {
                return 0;
            }
            char[] chs = str.toCharArray();
            int len = 0;
            for (int i = 0; i < chs.length; i++) {
                len += (chs[i] > 0xff) ? 2 : 1;
            }
            return len;
        }    public static int utf8ByteLength(String str) {
            if (str == null) {
                throw new IllegalArgumentException("str is null");
            }
            if (str.length() == 0) {
                return 0;
            }
            char[] chs = str.toCharArray();
            int len = 0;
            for (int i = 0; i < chs.length; i++) {
                if (chs[i] < 0x80) {
                    len++;
                } else if (chs[i] < 0x800) {
                    len += 2;
                } else if (chs[i] < 0x10000) {
                    len += 3;
                }
            }
            return len;
        }
    }
      

  3.   

    ...火龙果真的很用心...追问一下:
    我见表的字段属性就是varchar2(20),并没有区分byte和char还有按照gbk和utf8来区分如果解析中文吗???
    这个有区别吗???我的确是不懂就是了..麻烦再解释一下
      

  4.   

    直接test.getBytes(encode).length不就行了吗?
    写那么多干嘛
      

  5.   

    java中字符本身就占用两个字节!