zoukankan      html  css  js  c++  java
  • java StringBuilder案例

    实现输出字符串的长度,容量(容量不够则扩容),及内容

    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);
        }
    }
  • 相关阅读:
    高阶函数
    Vue-cli 3.0 搭建,以及vuex、axios、使用
    Git --- 基本操作以及Git 特殊命令,公司常用命令
    Git 剖析,以及Git相关操作
    git ssh key 生成
    React.Fragment 组件没有必要的多层嵌套,外层不需要过多嵌套
    spring cloud连载第三篇之Spring Cloud Netflix
    spring cloud连载第二篇之Spring Cloud Config
    AbstractQueuedSynchronizer
    Timer定时器
  • 原文地址:https://www.cnblogs.com/liubing2018/p/8483530.html
Copyright © 2011-2022 走看看