[求助] 获取一个字符串的字符长度,
例1:String s = "中文";System.out.println("长度为:"+s.length()); //这个地方会得到长度为2
我不想要这字符串的长度,我想要这字符串中字符长度。也就是4。
例2:String ss = "中123";// 这个地方想获取长度为5,不是4。不知各位明白了没???
搜索更多相关主题的帖子:
长度 获取 字符
----------------解决方案--------------------------------------------------------
s.length()
这个方法得到是字符的长度,不管你是中文还是英文
----------------解决方案--------------------------------------------------------
对啊!
s.length()是字符串长度,我想要的不是这个。
我想要的是字符串中的字节长度,比如:String s = "中123";字节长度是5,而用s.length()得到的是4.
明白了没??是字节长度,不是字符串的长度。
----------------解决方案--------------------------------------------------------
问题已解决:
例:
String str = "国123";
System.out.println("子节长度为:"+str.getBytes().length);
谢谢 zplove了,虽然这种方式没有很好的解决,怎样判断一个字符串中是否包含中文字符!对于当前问题到是个很好的答案!!
----------------解决方案--------------------------------------------------------
public class Test1 {
public static void main(String args[]){
String ss="国123";
System.out.println("length is ="+ss.getBytes().length);
System.out.println("length2 is="+ss.length());
}
}
结果:
length is =5
length2 is=4
----------------解决方案--------------------------------------------------------