package com.bjsxt.stringbuffer;
public class TestStringBuffer {
public static void main(String[] args ) {
// 实际上创建了一个长度为 16 的 char 类型的数组
StringBuffer sb1 = new StringBuffer ();
StringBuffer sb2 = new StringBuffer ( "hello" ); //str.length()+16 , char 类型的数组的长度为 21
System. out .println( " 最大容量 :" + sb2 .capacity());
//(1)append(...) 可以追加任何数据类型的数据
sb2 .append( "world" );
sb2 .append( "helloworld" );
sb2 .append( "world" ); //25? 个字符
System. out .println( sb2 ); // 调用了 toSring 方法 ()
System. out .println( " 最大容量 :" + sb2 .capacity());
/** 调用无参构造方法时,初始化 char 类型的数组的长度为 16 ,带参的构造方法,实始容量为 str.length()+16,
* 如果使用 append( 。。 ) 方法,向容量中添加数据时,超出了初始容量,将进行容量的自动扩充,
* 扩充的原理是 value=Arrays.copyOf(value, 新容量 ) , 新容量 = 原容量 *2+2 */
System. out .println( "sb2.length():" + sb2 .length());
// 容器基本都会具备增,删,改,查的方法
/** 增 :append(....) ,insert(....)
* 删 :delete( int start, int end) deleteCharAt( int index)
* 改 :setCharAt( int index,char a) ,replace( int start, int end,String str )
* 查 :
* */
sb2 .delete(2, 5); // 含头不含尾 , 将 2 到 4 的字符删除 , 依然是数组的拷贝 ,System.arraycopy(..)
System. out .println( sb2 );
sb2 .deleteCharAt(3);
System. out .println( sb2 );
sb2 .setCharAt(2, ' 中 ' );
System. out .println( sb2 );
sb2 .replace(2, 5, " 雾霾很严重 " );
System. out .println( sb2 );
System. out .println( sb2 .lastIndexOf( "o" ));
System. out .println( sb2 .lastIndexOf( "o" ,10));
sb2 .insert(2, "$" ); // 插入
System. out .println( sb2 );
sb2 .append( " 你好 " );
System. out .println( sb2 );
}
}
StringBuffer学习
猜你喜欢
转载自blog.csdn.net/wyqwilliam/article/details/92801409
今日推荐
周排行