StringBuffer类常用方法

 

StringBuffer类概述 

 

      1)我们如果对字符串进行拼接操作,每次拼接,都会构建一个新的String对象,既耗时,又浪费空间。而StringBuffer就可以解决这个问题
  2)线程安全的可变字符序列
  3)StringBuffer和String的区别
   前者长度和内容可变,后者不可变。
  · 如果使用前者做字符串的拼接,不会浪费太多的资源。


构造方法


· public StringBuffer() :无参构造方法
· public StringBuffer(int capacity) :指定容量的字符串缓冲区对象
· public StringBuffer(String str) :指定字符串内容的字符串缓冲区对象
 StringBuffer的方法:
 public int capacity():返回当前容量,理论值
  public int length():返回长度(字符数) ,实际值

package com.stringbuffer;

public class TestStringBufffer {

	public static void main(String[] args) {
		//StringBuffer构造方法1
		StringBuffer sb1=new StringBuffer("Hello");
		System.out.println(sb1);
		
		String s1="World";
		//StringBuffer构造方法2
		StringBuffer sb2=new StringBuffer(s1);
		System.out.println(sb2);
		
		//length()返回字符串的长度
		System.out.println(sb2.length());
		//toString()这个方法重写了Object中的toString()方法,返回String类型的字符串
		//输出StringBuffer对象时候,会默认调用此方法
		System.out.println(sb2);
		
		//append(String s)方法在原有的字符串后面添加字符串,返回的是添加后的StringBuffer对象
		sb1.append(" World");
		System.out.println(sb1);
		
		//public StringBuffer deleteCharAt(int index)
		//该方法的作用是删除指定位置的字符,然后将剩余的内容形成新的字符串
		sb1.deleteCharAt(0);
		System.out.println(sb1);//ello World
		
		//public StringBuffer delete(int start,int end)
		//从字符缓冲区中从start索引删除到end索引所对应的字符,其中包括start索引不包括end索引对应的值
		sb1.delete(1, 3);
		System.out.println(sb1);
		
		//public StringBuffer insert(int offset,String str)
		//在字符串缓冲区的第offset个字符后面插入指定字符串
		sb1.insert(1, "ME");
		System.out.println(sb1);
		
		//public StringBuffer reverse(),将字符串反转
		sb1.reverse();
		System.out.println(sb1);
		
		
		
	}

}

  

posted @ 2017-07-25 11:01  奔跑的经理  阅读(6153)  评论(0编辑  收藏  举报