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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章