看你要什么长度了,如果一个中文算1,直接用length()就可以了 如果要字节长度,就转成byte[]再取length,如:String s = ..... int l = s.getBytes("UTF-16").length;
java可是unicode哦,连类的名称都可以中文来表示
使用str.getbytes[]方法得到字节数组,然后调用length就可以了。 代码如下: public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String str = "test测试"; int len = str.getBytes().length; System.out.println(len); }}
String name = "测试test"; String hello ="你"; System.out.println(hello.getBytes("utf-8").length); System.out.println(name.length()); try { int i = name.getBytes("utf-8").length; System.out.println(i); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); }输出结果为 3 6 10中文是3个字节么?
JS中有个函数叫lenB()也可以 你试试
String name = "测试test"; String hello ="你"; System.out.println(hello.getBytes().length); System.out.println(name.length()); int i = name.getBytes().length; System.out.println(i); print :2 6 8 完全没问题
java数组是length
JS中是没有的哦。
java数组是length
byte bt[] = str.getBytes();
bt.length();
1个中文2个字节
如果要字节长度,就转成byte[]再取length,如:String s = .....
int l = s.getBytes("UTF-16").length;
代码如下:
public class Test { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "test测试";
int len = str.getBytes().length;
System.out.println(len);
}}
String hello ="你";
System.out.println(hello.getBytes("utf-8").length);
System.out.println(name.length());
try {
int i = name.getBytes("utf-8").length;
System.out.println(i);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}输出结果为
3
6
10中文是3个字节么?
String name = "测试test";
String hello ="你";
System.out.println(hello.getBytes().length);
System.out.println(name.length());
int i = name.getBytes().length;
System.out.println(i);
print :2
6
8
完全没问题
UTF-16编码下, 一个汉字被认作4个字节长度.
你可以用GBK 或者 GB2312试试 那是被当做2个字节的
UTF-16下一个汉字是2个字节
是不是吧每个字符串后面都加了个\n或者什么的
应该是无论汉字还是字母都是2个字节但是会给整个字符串的字节数加2
some_string.length();
统计字节
some_string.getBytes().length(); //缺省编码即可,除非启动java时指定编码参数启动,否则缺省就是unicode的
UTF-8所有汉字和中文标点都需要 3 个字节才能表达Windows 的内部其实是用的 UCS-2 标准,并用 UTF-16 来实现。而非 Windows 系统大多采用了 UTF-8 。UTF-8 在很多情况下更有优势,首先它不需要考虑大头小头的问题,其次,数据损坏的时候,不会有半个汉字的问题。并且 UTF-8 可以完整的表达 UCS-4 而不需要有额外的付出。
String hello = "你";
try {
System.out.println(hello.getBytes("UTF-16").length);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(TestFrame.class.getName()).log(Level.SEVERE, null, ex);
}System.out.println(hello.getBytes("UTF-16").length);
结果4
System.out.println(name.getBytes("UTF-16").length);结果14谁来解释下