UTF8ByteArrayUtils { public static int findNthByte(byte [] utf, int start, int length, byte b, int n) { int pos = -1; int nextStart = start; for (int i = 0; i < n; i++) { pos = findByte(utf, nextStart, length, b); if (pos < 0) { return pos; } nextStart = pos + 1; } return pos; }  static int findByte(byte [] utf, int start, int end, byte b); static int findBytes(byte [] utf, int start, int end, byte[] b); static int findNthByte(byte [] utf, int start, int length, byte b, int n); static int findNthByte(byte [] utf, byte b, int n);  }
@Test public void testFindNthByte() { byte[] data = "Hello, world!".getBytes(); assertEquals("Did not find 2nd occurrence of character 'l'", 3, UTF8ByteArrayUtils.findNthByte(data, 0, data.length, (byte) 'l', 2)); assertEquals("4th occurrence of character 'l' does not exist", -1, UTF8ByteArrayUtils.findNthByte(data, 0, data.length, (byte) 'l', 4)); assertEquals("Did not find 3rd occurrence of character 'l'", 10, UTF8ByteArrayUtils.findNthByte(data, (byte) 'l', 3)); }