java中StringBuffer的各种功能测试详解(1)

java中StringBuffer的各种功能测试详解(1)

  • StringBuffer的添加功能
  • public StiringBuffer append(String str);
  • 可以把任意类型数据添加到字符串缓冲区里面,并返回字符串缓冲区本身
class test{
	public static void main(String[] args){
		//创建一个字符串缓冲区	
		StringBuffer sb = new StringBuffer();
		
		StringBuffer sb2 = sb.append("hello");
		System.out.println("sb:"+sb);
		System.out.println("sb2:"+sb2);
		System.out.println(sb == sb2);
		//第一个输出结果为:sb:hello
		//第二个输出结果为:sb2:hello
		//第三个输出结果为:true
		//原因:创建一个字符串缓冲区,然后在缓冲区存入一个hello(StringBuffer sb2 = sb.append("hello") )
		//然后这个缓冲区就有一个hello的字符串,无论调用sb还是sb2,都会返回hello
		sb.append("hello");
		sb.append("true");
		sb.append(50);
		sb.append("34.56");
		System.out.println("sb:"+sb);
		//输出结果为:sb:hellotrue5034.56

	
		//链式编程
		sb.append("hello").append("true").append(50).append(34.56);
		System.out.println("sb:"+sb);
		//输出结果为:sb:hellotrue5034.56
		
	}
}

在指定位置添加
***public StringBuffer insert(int offset,String str) ***
在指定位置把任意类型的数据插入到字符串缓冲区里面,并返回字符串缓冲区本身

class tesst{
	public static void main(String[] args){
		StringBuffer sb = new StringBuffer();
	
		sb.append("hello").append("true").append(50).append(52.36);
		System.out.println("sb:"+sb);
		sb.insert(5,"world");
		System.out.println("sb:"+sb);
		//第一个输出结果为:sb:hellotrue5052.36
		//第二个输出结果为:sb:helloworldtrue5052.36
	}
}

StringBuffer的删除功能
public StringBuffer deleteCharAt(int index)
删除指定位置的字符,并返回本身
有删除就应该有添加没有添加怎么删除

class test{
	public static void main(String[] args){
		StringBuffer sb = new StringBuffer();
		
		sb.append("hello").append("true").append(50).append(52.36);
		System.out.println("sb:"+sb);
		//输出结果为:sb:hellotrue5052.36
		//要删除e
		sb.deleteCharAt(1);//这里是阿拉伯数字1
		System.out.println("sb:"+sb);
		//输出结果为:sb:hllotrue5052.36
		//如果我要继续删除第一个l怎么办
		sb.deleteCharAt(1);//这里还是阿拉伯数字1
		System.out.println("sb:"+sb);
		//输出结果为:sb:hlotrue5052.36
	}
}

在指定位置删除
public StringBuffer delete(int start,int end)
删除从指定位置开始指定位置结束的内容,并返回本身

class test{
	public static void main(String[] args){
		StringBuffer sb = new StringBuffer();
		
		sb.append("hello").append("world").append("true").append(50).append(52.36);
		System.out.println("sb:"+sb);
		//输出结果为:sb:helloworldtrue5052.36
		//要删除world这个字符
		sb.delete(5,10);//包前不包后
		System.out.println("sb:"+sb);
		//输出结果为:sb:hellotrue5052.36
		//要删除所有数据
		sb.delete(0,sb.length());
		System.out.println("sb:"+sb);
		//输出结果为:sb:

	}
}

你可能感兴趣的:(java中StringBuffer的各种功能测试详解(1))