Android(Java):String

4个字符 “我们”算几个字符?

 

计算字符串的字节数:

getBytes()length//UTF-8编码下一个字占3个字节

getBytes("gb2312").length//gb2312编码下一个字占2个字节

 public byte[] getBytes(Charset charset) {
        String canonicalCharsetName = charset.name();
        if (canonicalCharsetName.equals("UTF-8")) {
            return Charsets.toUtf8Bytes(value, offset, count);
        } else if (canonicalCharsetName.equals("ISO-8859-1")) {
            return Charsets.toIsoLatin1Bytes(value, offset, count);
        } else if (canonicalCharsetName.equals("US-ASCII")) {
            return Charsets.toAsciiBytes(value, offset, count);
        } else if (canonicalCharsetName.equals("UTF-16BE")) {
            return Charsets.toBigEndianUtf16Bytes(value, offset, count);
        } else {
            CharBuffer chars = CharBuffer.wrap(this.value, this.offset, this.count);
            ByteBuffer buffer = charset.encode(chars.asReadOnlyBuffer());
            byte[] bytes = new byte[buffer.limit()];
            buffer.get(bytes);
            return bytes;
        }
    }

--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

本文将用3个图片来解释Java中String的不可变性().
1. 声明String对象

  1. String s = "abcd";  
String s = "abcd";
图1
2. 将一个字符串变量赋值给另一个String变量
  1. String s2 = s;  
String s2 = s;
图2
3. 字符串连接
  1. s = s.concat("ef");  
  2. // s = s + "ef"; // 等价  
s = s.concat("ef");
// s = s + "ef"; // 等价
图3
总结:
一个String对象在 堆内存 中创建以后, 就不能被改变了. 请注意String对象的所有方法都不会改变其本身,而是会返回一个新的String对象.
如果我们需要可改变的字符串,则需要使用 StringBuffer 或者 StringBuilder. 否则每次创建一个新String对象的话,就会造成大量的内存浪费,需要耗时来执行垃圾回收。可以参考: StringBuilder的使用示例

相关文章:
1.  十大常见Java String问题
2. Java Code – Convert a file to a String
3. String is passed by “reference” in Java
4. The interface and class hierarchy diagram for collections with an example program
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值