源代码

class SequentialString {
    constructor(str = "") {
        this.data = Array.from(str); // 内部使用数组存储字符
    }

    // 判断串是否为空
    isEmpty() {
        return this.data.length === 0;
    }

    // 求串长
    length() {
        return this.data.length;
    }

    // ... existing code ...

    // 将串转换为字符串
    toString() {
        return this.data.join("");
    }
}

// 测试代码
const str1 = new SequentialString("hello");
const str2 = new SequentialString("world");
const str3 = new SequentialString("lo");

console.log("str1 是否为空?", str1.isEmpty());
console.log("str1 的长度:", str1.length());
console.log("str1 的子串 (1, 4):", str1.getSubstring(1, 4).toString());
console.log("str1 是否等于 str2?", str1.isEqual(str2));
console.log("str3 是否是 str1 的子串?", str3.isSubstringOf(str1));
console.log("str3 在 str1 中的位置:", str1.indexOf(str3));
console.log("反转 str1:", str1.reverse().toString());
console.log("在 str1 的索引 2 处插入 'abc':", str1.insert(2, new SequentialString("abc")).toString());
console.log("从 str1 中删除索引 2 到 5 的子串:", str1.deleteSubstring(2, 5).toString());
console.log("在 str1 中将 'lo' 替换为 'xx':", str1.replace(str3, new SequentialString("xx")).toString());
console.log("清空 str1:", str1.clear().toString());

运行结果

str1 是否为空? false str1 的长度: 5 str1 的子串 (1, 4): ell str1 是否等于 str2? false str3 是否是 str1 的子串? true str3 在 str1 中的位置: 3 反转 str1: olleh 在 str1 的索引 2 处插入 'abc': heabcllo 从 str1 中删除索引 2 到 5 的子串: heclo 在 str1 中将 'lo' 替换为 'xx': hecxx 清空 str1: ""