Java 实现简单动态字符串

Java 实现简单动态字符串

用 Java 实现简单动态字符串(Simple Dynamic String,SDS)结构体的示例代码:

java 复制代码
import java.util.Arrays;

public class SDS {
    // 字符串结束字符
    private static char endChar = '\0';
    // 字符串长度
    private int len;
    // buf数组中未使用的字节数
    private int free;
    // 字节数组
    private char[] buf;

    // 构造函数
    public SDS(String str) {
        this.len = str.length();
        this.buf = Arrays.copyOf(str.toCharArray(), this.len + 1);
        this.buf[this.len] = endChar;
        this.free = buf.length - len - 1;
    }

    // 获取buf数组
    public char[] getBuf() {
        return buf;
    }

    // 拼接字符串 sdscat 方法用于拼接字符串,实现了空间预分配策略。
    public void sdscat(String str) {
        char[] strTemp = str.toCharArray();
        int strTempLen = str.length();
        int lastLen = this.len + strTempLen;
        // 先判断长度
        if (lastLen < 1 * Math.pow(2, 20)) {
            // 小于1MB(2^20B),那么free空间=len大小,buf的实际长度为2*len+1
            this.free = lastLen;
        } else {
            // 大于1MB(2^20B),那么free空间=1MB,buf的实际长度为1MB+len+1
            this.free = (int) Math.pow(2, 20);
        }
        this.len = lastLen;
        // 拼接数组
        char[] originChar = this.toString().toCharArray();
        char[] result = Arrays.copyOf(originChar, lastLen);
        System.arraycopy(strTemp, 0, result, originChar.length, strTemp.length);
        this.buf = Arrays.copyOf(result, lastLen + 1);
        this.buf[lastLen] = endChar;
    }

    public int getLen() {
        return len;
    }

    public void setLen(int len) {
        this.len = len;
    }

    public int getFree() {
        return free;
    }

    public void setFree(int free) {
        this.free = free;
    }
   // toString 方法用于将 SDS 对象转换为字符串表示形式。
    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder("");
        for (int i = 0; i < this.buf.length; i++) {
            if (this.buf[i]!= endChar ) {
                stringBuilder.append(this.buf[i]);
            }
        }
        return stringBuilder.toString();
    }
}

测试:

java 复制代码
public class TestSDS {
    public static void main(String[] args) {
         SDS sds = new SDS("a a");
        System.out.println(sds.getLen() +","+ sds.getFree());
        char[] a = sds.getBuf();
        for (char aTemp : a) {
            System.out.println(aTemp);
        }
    }
}
相关推荐
西西弗Sisyphus37 分钟前
全面掌握Python时间处理
python·time
小梁不秃捏3 小时前
深入浅出Java虚拟机(JVM)核心原理
java·开发语言·jvm
java1234_小锋3 小时前
一周学会Flask3 Python Web开发-http响应状态码
python·flask·flask3
我不是程序猿儿3 小时前
【C】识别一份嵌入式工程文件
c语言·开发语言
奔跑吧邓邓子4 小时前
【Python爬虫(12)】正则表达式:Python爬虫的进阶利刃
爬虫·python·正则表达式·进阶·高级
码界筑梦坊4 小时前
基于Flask的京东商品信息可视化分析系统的设计与实现
大数据·python·信息可视化·flask·毕业设计
软件开发技术局4 小时前
撕碎QT面具(8):对控件采用自动增加函数(转到槽)的方式,发现函数不能被调用的解决方案
开发语言·qt
pianmian14 小时前
python绘图之箱型图
python·信息可视化·数据分析
csbDD5 小时前
2025年网络安全(黑客技术)三个月自学手册
linux·网络·python·安全·web安全
周杰伦fans6 小时前
C#中修饰符
开发语言·c#