实现输出字符串的长度,容量(容量不够则扩容),及内容
import java.util.Arrays; public class MyStringBuilderDemo { //任务:存储字符串并输出长度及容量 public static void main(String[] args) { // TODO Auto-generated method stub MyStringBuilder msb = new MyStringBuilder(); 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;//字符串的长度 public int length() { return count; } public int capacity() { return value.length; } public MyStringBuilder(){//默认给定数组容量为16 value = new char[16]; } public MyStringBuilder(int capacity){//默认给定数组容量为16 value = new char[capacity]; } //追加字符串 public MyStringBuilder append(String str) { int len = str.length(); addength(count+len); //追加字符串 追加的字符串.getChars(追加字符串的起始位置,结束为止,目标字符串,开始写入的位置) str.getChars(0, str.length(), value, count); count+=len; return this; } private void addength(int capacity) {//防止字符串长度不够,扩容数组 if(capacity -value.length>0) { int newlength; newlength = value.length*2+2; value = Arrays.copyOf(value, newlength); } } //输出字符串 public String toString() { return new String(value,0,count); } }