开发者

Finding string into a ByteArray. Is it a simple solution for that?

What is th开发者_StackOverflow社区e simpliest way to find an occurance of some sequance of bytes (string) in a long byte array?

thank you in advance!!

UPD: I tried to do

my_byte_array.toString().indexOf(needle_string);

the problem is that in flash/air string consist of utf8 characters, so indexOf will return value different from offset of "string" in a byte array (actually it's zip archive)


Assuming the array is long enough that you don’t want to convert it to a string, I guess I’d just bite the bullet and do something like this:

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
}


I believe this would work:

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

This will return -1 if the sequence is not found, and otherwise the index at which the sequence has been found.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜