/*
4.
StringBuffer与StringBuilder
StringBuffer与StringBuilder的方法相同
StringBuffer是线程安全的,效率低
StrungBuilder是线程不安全的,效率高
以下以StringBuffer做演示
*/
class Test
{
public static void main(String[] args)
{
System.out.println("----------构造方法-----------");
gouZaoFunction();
System.out.println("\n-----------给StringBuffer中的指定字符赋值---------");
setCharAt();
System.out.println("\n-----------插入字符串---------");
insert();
System.out.println("\n-----------截取字符串---------");
substring();
System.out.println("\n-----------删除子串---------");
delete();
System.out.println("\n-----------倒置字符串---------");
resever();
System.out.println("\n-----------删除重复的字符----------");
deletes();
}
/*
构造方法
*/
public static void gouZaoFunction(){
StringBuffer sb = new StringBuffer(); //默认底层数组长度为16个
StringBuffer sb1 = new StringBuffer(6); //指定底层数组初始空间
StringBuffer sb2 = new StringBuffer("Hello,I'M StringBuffer");//根据指定String类对象,构造StringBuffer对象
System.out.println("StringBuffer():"+sb);
System.out.println("StringBuffer():"+sb1);
System.out.println(sb2);
}
/*
给StringBuffer中的指定字符赋值
*/
public static void setCharAt(){
StringBuffer sb = new StringBuffer("我叫周鑫柯,我是男生");
System.out.println(sb);
sb.setCharAt(8,'女');
System.out.println(sb);
System.out.println("发生了什么?");
}
/*
在SringBuffer指定位置,插入指定内容
*/
public static void insert(){
StringBuffer sb = new StringBuffer("I You");
System.out.println("小伙去表白有点紧张 "+sb);
System.out.println("2货,漏单词了");
sb.insert(1," Love");
System.out.println("小伙灵机一动:"+sb);
}
/*
截取字符串
*/
public static void substring(){
StringBuffer sb = new StringBuffer("My name is: XinKe Zhou");
System.out.println("自我介绍一下:\n"+sb);
System.out.println("Fuck! 我不懂英语,来个翻译,他叫什么什么名字?");
System.out.println("周总您好,他叫"+sb.substring(sb.indexOf(":")+1));
}
/*
删除子串
*/
public static void delete(){
StringBuffer sb = new StringBuffer("Fuck! 你踩到我的脚了");
System.out.println(sb);
System.out.println("周总,讲粗话不礼貌!");
System.out.println("抱歉!!"+sb.delete(0,6));
}
/*
倒置字符串
*/
public static void resever(){
StringBuffer sb =new StringBuffer("12345");
System.out.println(sb);
sb.reverse();
System.out.println(sb);
}
/*
删除重复的字符串
*/
public static void deletes(){
StringBuffer sb = new StringBuffer("hello whorld");
System.out.println(sb);
for (int i=0;i<sb.length();i++)
{
char c = sb.charAt(i);
for (int j=i+1;j<sb.length() ;)
{
if(sb.charAt(j)==c){
sb.deleteCharAt(j);
continue;
}
j++ ;
}
}
System.out.println(sb);
}
}
|