/**

  • Searches for a byte array within another byte array starting from a specific index.
  • Assumes both arrays contain ASCII characters (Latin-1 encoding).
  • @param src The source byte array to search in.
  • @param srcCount The number of bytes in the source byte array.
  • @param tgt The target byte array to search for.
  • @param tgtCount The number of bytes in the target byte array.
  • @param fromIndex The index to start searching from in the source byte array.
  • @return The index of the first occurrence of the target byte array in the source byte array, or -1 if not found.
  • @throws NullPointerException if src or tgt are null.
  • @throws IndexOutOfBoundsException if fromIndex is negative or greater than srcCount.
  • @throws IllegalArgumentException if tgtCount is larger than tgt.length or srcCount is less than tgtCount. */ public static int indexOf(byte[] src, int srcCount, byte[] tgt, int tgtCount, int fromIndex) { Objects.requireNonNull(src, 'src must not be null'); Objects.requireNonNull(tgt, 'tgt must not be null'); if (fromIndex < 0 || fromIndex > srcCount) { throw new IndexOutOfBoundsException('fromIndex is out of bounds: ' + fromIndex); } if (tgtCount > tgt.length) { throw new IllegalArgumentException('tgtCount is larger than tgt.length'); } if (srcCount < tgtCount) { throw new IllegalArgumentException('srcCount is less than tgtCount'); } if (tgtCount == 0) { return fromIndex; } byte first = tgt[0]; int max = srcCount - tgtCount; for (int i = fromIndex; i <= max; i++) { if (src[i] != first) { while (++i <= max && src[i] != first); } if (i <= max) { int j = i + 1; int end = j + tgtCount - 1; for (int k = 1; j < end && src[j] == tgt[k]; j++, k++); if (j == end) { return i; } } } return -1; }
Java Byte Array Search: Efficiently Find Subsequences with indexOf()

原文地址: https://www.cveoy.top/t/topic/mQfk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录