在Uint8Array中查找字符串的索引

问题描述

我有一个Uint8Array,它实际上是PDF文件内容。我想找到位于该数组中的某些字符串的索引,以便可以在该位置插入一些内容

为此,我实际上是将Uint8Array转换为字符串,然后在该字符串中搜索我想为其找到索引的字符串。

这是代码

    const pdfStr = new TextDecoder('utf-8').decode(array);
    
    // find Byterange
            const byterangePos = this.getSubstringIndex(pdfStr,'/Byterange [',1);
            if (byterangePos === -1) {
                throw new Error(
                    'Failed to locate Byterange.'
                );
            }
    
           getSubstringIndex = (str,substring,n) => {
            let times = 0,index = null;
    
            while (times < n && index !== -1) {
                index = str.indexOf(substring,index + 1);
                times++;
            }
    
            return index;
        }

array = this.updateArray(array,(byterangePos + '/Byterange '.length),byterange);

我遇到的问题是utf-8字符以可变长度(1-4个字节)的字节进行编码,因此我得到的字符串的长度小于UInt8Array本身的长度,因此通过搜索字符串得到的索引与UInt8Array中的'/ Byterange'字符串的实际位置不匹配,因此它应在应该插入的位置之前插入。

有什么方法可以获取UInt8Array的1字节字符串表示形式,例如ASCII还是类似的东西?

解决方法

我通过更改解决了问题

const pdfStr = new TextDecoder('utf-8').decode(array);

const pdfStr = new TextDecoder('ascii').decode(array);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...