在ByteArray中查找字符串。这是一个简单的解决方案吗?

时间:2011-10-03 10:18:10

标签: flash actionscript-3 air bytearray

在长字节数组中找到一些字节序列(字符串)的最简单方法是什么?

提前谢谢!!

UPD:我试图

my_byte_array.toString().indexOf(needle_string);

问题是flash / air字符串由utf8字符组成,所以indexOf将返回与字节数组中“string”的偏移量不同的值(实际上是zip存档)

2 个答案:

答案 0 :(得分:1)

我相信这会奏效:

//needle_string is the sequence you want to find
my_byte_array.toString().indexOf(needle_string);

如果未找到序列,则返回-1,否则返回序列的索引。

答案 1 :(得分:1)

假设数组足够长,你不想把它转换为字符串,我想我只是咬紧牙关做这样的事情:

function byteArrayContainsString
  (haystack : ByteArray, needleString : String) : Boolean
{
  const needle : ByteArray = new ByteArray

  needle.writeUTFBytes(needleString)

  return byteArrayIndexOf(haystack, needle) !== -1
}

function byteArrayIndexOf
  (haystack : ByteArray, needle : ByteArray) : int
{
  search: for (var i : int = 0; i < haystack.length; ++i) {
    for (var j : int = 0; j < needle.length; ++j)
      if (haystack[i + j] !== needle[j])
        continue search

    return i
  }

  return -1
}