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

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

app substr 創建 插入 poj reverse () 反轉 lac

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);
		
	}
	
}

  

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