1. 程式人生 > >JAVA高階特性--String/StringBuffer/Builder

JAVA高階特性--String/StringBuffer/Builder

String

 String物件一旦建立就不能改變 是常量

需要進行大量字串操作應採用StringBuffer/StringBuilder  最終結果轉換成String物件

StringBuffer

執行緒安全的  可變字元序列

一個類似於String的字串緩衝區(字元陣列)

 

常用方法

  length(  )  返回容器(字元)個數

       capacity()容量

  append(String str )  新增字元

  insert(int offset, String str)在指定字元插入字元

  indexof(String str)在字元陣列首次出現 的下標

      indexof(String str,int fromIndex)查詢字串首次出現的位置,從某個位置開始

     lastindexof(String str)在字元陣列最後出現 的下標

  reverse( )字元反轉

  toString()轉換為對應的字串

StringBuilder 

執行緒不安全的 單執行緒使用   與StringBuffer相比通常優先於StringBuilder,因為它支援所有相同的操作,但因為它不執行同步,所以更快

package com.pojo;

public class StringBuilderDemo {
  public static void main(String[] args) {
	//StringBuilder sb="abc";//不相容的型別
	//StringBuilder sb=new StringBuilder();//預設16個字元大小的容量
	//StringBuilder sb=new StringBuilder();//初始化100容量大小
	//StringBuilder sb=new StringBuilder("abc");
	  StringBuilder sb=new StringBuilder();
	  sb.append("hello");
	  sb.append(1.5);
	  sb.append(true);
	  System.out.println(sb.length());
	  System.out.println(sb.capacity());//容量大小
	  System.out.println(sb.insert(5, "word"));
	  System.out.println(sb.reverse());//反轉
	  System.out.println(sb.replace(5, 7, "111"));
	  System.out.println(sb.substring(1, 2));//擷取字串
	  System.out.println(sb.indexOf("rt"));
}
}

  

案例

package com.pojo;

import java.util.Arrays;

public class MyStringBuilder {
   public static void main(String[] args) {
	   MyStringBuilderDemo m=new MyStringBuilderDemo();
	   m.append("hello");
	   m.append(",java");
	   m.append("123456");
	   System.out.println(m.length()+""+m.capacity()+""+m.toString());
}
}

class MyStringBuilderDemo{
	private char[]  value;//字元陣列
	private int count=0;//字元陣列中存放字元的個數
	public MyStringBuilderDemo() {
		value=new char[16];
	}
	public MyStringBuilderDemo(int  capacity) {
		value=new char[capacity];
	}
	
	public MyStringBuilderDemo(String str) {
		value=new char[str.length()+16];
	}
	//得到字元陣列中的字元個數
	public int  length() {
		return count;
	}
	//返回容器的容器大小
	public int capacity() {
		return value.length;
		
	}
	//實現字串的新增
	public MyStringBuilderDemo append(String str) {
		
	   int len=str.length();//獲取要新增字串的長度
		//確保字元陣列能放進去所新增的字串	
	   ensureCapacity(count+len);
	   //把要新增的字串追加到新的指定陣列的指定位置後面
	   str.getChars(0, len,value ,count);
	   count+=len;//元素個數增加了
	    return this;
	}
	
	private void ensureCapacity(int Capacity) {
		//資料超出容量大小  擴容
		if (Capacity-value.length>0) {
			int newCapacity=value.length*2+2;//擴容後新字元陣列的大小
			value=Arrays.copyOf(value, newCapacity);
		}
	}
	//把字元陣列轉換成字串顯示
	public String toString() {
		return new String(value, 0, count);
		
	}
	
}