字符串长度都是调用String类的length()方法,通常这样就可以,但是现在项目中需要汉字的长度是2,所以说需要换个写法

public static int stringLength(String str) {
        int stringLength = 0;
        try {
            if (str != null && !"".equals(str)) {
                stringLength = str.getBytes("GB18030").length;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return stringLength;
    }

这样就可以了

 		String s = "hello 你好";
 		// 这种方法也行
        String str1 = new String(s.getBytes("GBK"),"iso-8859-1");
		
        System.out.println(str1.length());
        System.out.println(stringLength(s));

10
10

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-05
  • 2021-10-03
  • 2022-01-05
  • 2022-12-23
  • 2021-10-10
  • 2021-05-30
猜你喜欢
  • 2021-11-25
  • 2022-12-23
  • 2021-11-29
  • 2021-06-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案