Java examples for java.lang:byte Array
Find the first occurrence of sub in b Work in progress
/*/*from ww w . j a va 2 s . com*/ This file is part of p300. p300 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. p300 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with p300. If not, see <http://www.gnu.org/licenses/>. */ //package com.java2s; public class Main { public static void main(String[] argv) throws Exception { byte[] b = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 }; byte[] sub = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 }; System.out.println(indexOf(b, sub)); } /** * Find the first occurrence of sub in b * Work in progress * @param b * @param sub * @return Position of the first match or -1 if not found */ public static int indexOf(byte[] b, byte[] sub) { if (b == null || sub == null) { return -1; } for (int i = 0; i < b.length - sub.length + 1; i++) { boolean matches = true; for (int j = 0; j < sub.length; j++) { if (b[i + j] != sub[j]) { matches = false; } } if (matches) { return i; } } return -1; } }