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);
        }
    }
}
相关推荐
CHEN5_02几秒前
【Java基础】反射,注解,异常,Java8新特性,object类-详细介绍
java·开发语言
Cx330❀12 分钟前
【数据结构初阶】--排序(四):归并排序
c语言·开发语言·数据结构·算法·排序算法
云间月131417 分钟前
飞算JavaAI智慧文旅场景实践:从景区管理到游客服务的全链路系统搭建
java·开发语言
盖世英雄酱5813617 分钟前
必须掌握的【InheritableThreadLocal】
java·后端
找不到、了23 分钟前
JVM的逃逸分析深入学习
java·jvm
深盾安全35 分钟前
Python脚本安全防护策略全解析(上)
python
杜子不疼.35 分钟前
《Python学习之使用标准库:从入门到实战》
开发语言·python·学习
用户03321266636737 分钟前
Java 查找并替换 PDF 中的文本:高效自动化处理指南
java
意疏39 分钟前
【C语言篇】srand函数的详细用法解析
c语言·开发语言
胡耀超1 小时前
从哲学(业务)视角看待数据挖掘:从认知到实践的螺旋上升
人工智能·python·数据挖掘·大模型·特征工程·crisp-dm螺旋认知·批判性思维