基本介绍
即 StringBuffer 是存在堆中的而非常量池中的。(value 数组存放字符串内容)
与 String 的对比
StringBuffer:不用每次更新地址,但当数组空间不够时,会扩大并且更新地址。
构造器
StringBuffer stringBuffer = new StringBuffer();
StringBuffer stringBuffer1 = new StringBuffer(100);
StringBuffer hello = new StringBuffer("hello");
与 String 的相互转换
//String->StringBuffer
String s = "hello world";
//1 构造器
StringBuffer b1 = new StringBuffer(s);
//2 函数,append:附加,增补
StringBuffer b2 = new StringBuffer();
b2.append(s);
//StringBuffer->String
StringBuffer b = new StringBuffer("hello!");
//1 函数
String s1 = b.toString();
//2 构造器
String s2 = new String(b);
常用方法
StringBuffer的方法索引同样为左闭右开。
索引如果找不到,返回-1
课后练习
将价格按照格式输出:
法一:
String price = "1234567.59";
StringBuffer sb = new StringBuffer(price);
//找到小数点索引
int i = sb.lastIndexOf(".");
while(i-3 > 0){
sb.insert(i-3,",");
i -= 3;
}
法二:
for (int j = sb.lastIndexOf(".")-3; j > 0 ; j-=3) {
sb.insert(j,",");
}
System.out.println(sb);
标签:13,String,StringBuffer,常用,索引,new,sb,hello
From: https://www.cnblogs.com/gknives/p/18417388