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);
        }
    }
}
相关推荐
java叶新东老师4 分钟前
idea提交时忽略.class、.iml文件和文件夹或目录的方法
java·开发语言
飞翔的佩奇11 分钟前
Java项目:基于SSM框架实现的社区团购管理系统【ssm+B/S架构+源码+数据库+毕业论文+答辩PPT+远程部署】
java·数据库·vue.js·毕业设计·mybatis·答辩ppt·社区团购
走过,莫回头18 分钟前
在OpenMP中,#pragma omp的使用
开发语言·openmp
TDengine (老段)23 分钟前
TDengine 转化函数 TO_TIMESTAMP 用户手册
java·大数据·数据库·物联网·时序数据库·tdengine·涛思数据
Warren9828 分钟前
Java Collections工具类
java·开发语言·笔记·python·学习·oracle·硬件工程
love530love33 分钟前
Windows 11 下 Anaconda 命令修复指南及常见问题解决
运维·ide·人工智能·windows·python·架构·conda
NeoFii33 分钟前
Day 24:元组与os模块
python·机器学习
java叶新东老师44 分钟前
CMakelists.txt 实现多级目录编译
java·服务器·数据库
_风不会停息1 小时前
JDK1.8升级 JDK21 实践踩坑
java
半新半旧1 小时前
1.DRF 环境安装与配置
python·django