如何判断一个中文字符串的长度

zhyl1979 2004-11-05 12:11:42
下面这段代码输出的结果是:3
可是我希望的是他的unicode的长度。如何做?
谢谢!
public class temp
{
String str="你好啊";
public temp()
{
System.out.println(str.length());
}

public static void main(String args[])
{
temp obj=new temp();
}
}
...全文
394 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
PoemCode 2004-11-05
  • 打赏
  • 举报
回复
来看一下文档:
length

public int length()

Returns the length of this string. The length is equal to the number of 16-bit Unicode characters in the string.

Specified by:
length in interface CharSequence

Returns:
the length of the sequence of characters represented by this object.

注意这么一句话:
The length is equal to the number of 16-bit Unicode characters in the string.
一个汉字只占一个 16-bit Unicode
haroyy 2004-11-05
  • 打赏
  • 举报
回复
Unicode中文长度是不会变的,英文字母从1字节变为2字节
treeroot 2004-11-05
  • 打赏
  • 举报
回复
它的Unicode长度就是3呀每个Unicode占用2个字节,字节数是6
realfish 2004-11-05
  • 打赏
  • 举报
回复
package wuziqi;

import java.io.UnsupportedEncodingException;

public class temp
{
String str="你好啊";
public temp()
{

try {
byte[] a = str.getBytes("UTF-8");
System.out.println(a.length);
} catch (UnsupportedEncodingException e) {
}

}

public static void main(String args[])
{
temp obj=new temp();
}
}
realfish 2004-11-05
  • 打赏
  • 举报
回复
楼主应该是要UTF-8的长度,是1-6变长编码,我上面的编码可行。
我觉得楼主在做插入数据库之前的长度判断。
土不锅锅 2004-11-05
  • 打赏
  • 举报
回复
看看这个例子:
import java.io.*;
public class StringTest
{
public static void main(String[] args)
{
String aString = "这是一个测试串,This is a test string.";
String anotherString = null;
try {
anotherString = new String(aString.getBytes("GBK"), "ISO8859_1");
}
catch (UnsupportedEncodingException ex) {}
System.out.println(aString.length() + "," + anotherString.length());
}
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧