Java字符串处理之StringBuilder

import java.util.Arrays;


public class MyStringBuilderDemo {


public static void main(String[] args) {
// TODO Auto-generated method stub
Mystringbuilder msb = new Mystringbuilder();// 默认大小是16
msb.append("hello").append(",java").append("1234567");
System.out.println("字符个数:" + msb.length());
System.out.println("总容量大小" + msb.capacity());
System.out.println(msb.toString());
}


}


class Mystringbuilder {
private char[] value;// 字符数组
private int count = 0;// 字符数组中存放字符的个数
// 构造方法初始化


public Mystringbuilder() {
value = new char[16];
}


public Mystringbuilder(int capacity) {
value = new char[capacity];
}


public Mystringbuilder(String str) {
value = new char[str.length() + 16];
}


// 得到字符数组中字符的个数
public int length() {
return count;
}


// 返回容器的容量大小
public int capacity() {
return value.length;
}


// 实现字符串的追加
public Mystringbuilder append(String str) {
// 获取要添加字符串的长度
int len = str.length();
// 确保字符数组能放进去所添加的字符串
ensureCapacity(count + len);
// 把要添加的字符串追加到新的指定数组的指定位置的后面
str.getChars(0, len, value, count);
count += len;// 元素的个数增加了
// 返回当前你创建的动态字符串
return this;


}


private void ensureCapacity(int capacity) {
// 数据超出容量大小
if (capacity - value.length > 0) {
int newcapacity = value.length * 2 + 2;// 扩容后新字符数组的大小
// 数组的拷贝
value = Arrays.copyOf(value, newcapacity);
}
}


// 把字符数组的字符转换成字符串显示
public String toString() {


return new String(value, 0, count);


}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值