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);
        }
    }
}
相关推荐
低代码布道师5 分钟前
第五部分:第一节 - Node.js 简介与环境:让 JavaScript 走进厨房
开发语言·javascript·node.js
百锦再16 分钟前
大数据技术的主要方向及其应用详解
大数据·linux·网络·python·django·pygame
API小爬虫17 分钟前
淘宝按图搜索商品(拍立淘)Java 爬虫实战指南
java·爬虫·图搜索算法
盛夏绽放21 分钟前
Python字符串常用方法详解
开发语言·python·c#
lyrhhhhhhhh26 分钟前
Spring 框架 JDBC 模板技术详解
java·数据库·spring
亚林瓜子1 小时前
AWS Elastic Beanstalk控制台部署Spring极简工程
java·spring·云计算·aws·eb
noravinsc1 小时前
django中用 InforSuite RDS 替代memcache
后端·python·django
2401_cf1 小时前
如何创建maven项目
java·maven·intellij-idea
好吃的肘子2 小时前
Elasticsearch架构原理
开发语言·算法·elasticsearch·架构·jenkins
胡耀超2 小时前
霍夫圆变换全面解析(OpenCV)
人工智能·python·opencv·算法·计算机视觉·数据挖掘·数据安全