2020-02-29 String#length

参考:https://colobu.com/2019/01/04/how-many-charactors-in-a-java-string/

https://www.ibm.com/developerworks/cn/java/j-lo-chinesecoding/index.html

    //获取系统默认编码
    System.out.println("系统默认编码:" + System.getProperty("file.encoding")); //查询结果UTF-8
    //系统默认字符编码
    System.out.println("系统默认字符编码:" + Charset.defaultCharset()); //查询结果UTF-8
    //操作系统用户使用的语言
    System.out.println("系统默认语言:" + System.getProperty("user.language")); //查询结果zh

    System.out.println();

// String s1 = "hi,我来了";
String s1 = "a b c";

    String urf16 = new String(s1.getBytes(), Charset.forName("UTF-16"));
    System.out.println(urf16.length());
    System.out.println(urf16.getBytes("UTF-16").length);
    System.out.println(urf16.toCharArray().length);

    for (char c : urf16.toCharArray()) {
        System.out.println(c);
    }

    for (int c : urf16.toCharArray()) {
        System.out.print(c + " ");
    }
    System.out.println("\n======defaultCharset=====");

    String utf8 = new String(s1.getBytes(), Charset.forName("UTF-8"));
    System.out.println(utf8.length());
    System.out.println(utf8.getBytes("UTF-8").length);
    System.out.println(utf8.toCharArray().length);

    for (int c : utf8.toCharArray()) {
        System.out.print(c + " ");
    }
    System.out.println("\n======utf-8======");

    String gbk = new String(s1.getBytes(), Charset.forName("GBK"));
    System.out.println(gbk.length());
    System.out.println(gbk.getBytes("GBK").length);
    System.out.println(gbk.toCharArray().length);

    for (int c : gbk.toCharArray()) {
        System.out.print(c + " ");
    }
    System.out.println("\n======gbk======");

    String gb2312 = new String(s1.getBytes(), Charset.forName("GB2312"));
    System.out.println(gb2312.length());
    System.out.println(gb2312.getBytes("GB2312").length);
    System.out.println(gb2312.toCharArray().length);

    for (int c : gb2312.toCharArray()) {
        System.out.print(c + " ");
    }
    System.out.println("\n======gb2312======");

你可能感兴趣的:(2020-02-29 String#length)