I think you can do what you need by turning your array into Collection
. If you do not want to use Collections
, and you only deal with byte[]
, you can do it something like this:
public class A { public static byte[] deleteSubarray(byte[] array, byte[] subArray) { int p = searchFor(array, subArray); if (p == -1) return array; byte[] result = new byte[array.length - subArray.length + 1]; for (int i = 0; i < p; i++) result[i] = array[i]; for (int i = p + subArray.length - 1; i < array.length; i++) { result[p] = array[i]; p++; } return result; } public static byte[] insertElementAt(byte[] array, byte element, int position) { byte[] result = new byte[array.length + 1]; for (int i = 0; i <= position - 1; i++) result[i] = array[i]; result[position] = element; for (int i = position + 1; i < array.length; i++) { result[i] = array[i]; } return result; } public static byte[] searchAndReplace(byte[] array, byte[] search, byte[] replace) { if (search.length != replace.length) return array; int p = searchFor(array, search); if (p == -1) return array; byte[] result = Arrays.copyOf(array, array.length); for (int i = 0; i < replace.length; i++) { result[p] = replace[i]; p++; } return result; } public static int searchFor(byte[] array, byte[] subArray) { if (subArray.length > array.length) return -1; int p = (new String(array)).indexOf(new String(subArray)); for (int i = 1; i < subArray.length; i++) { if (array[p + i] != subArray[i]) return -1; } return p; } public static void main(String[] args) { String a = "hello world!"; String b = "lo w"; System.out.println(searchFor(a.getBytes(), b.getBytes())); System.out.println(new String(searchAndReplace(a.getBytes(), b.getBytes(), "mn x".getBytes()))); System.out.println(new String(insertElementAt(a.getBytes(), "-".getBytes()[0], 5))); System.out.println(new String(deleteSubarray(a.getBytes(), b.getBytes()))); } }
Conclusion:
3 helmn xorld! hello-world! helworld!
If you are dealing with other types of arrays, then searchFor
does not work, but you can easily generalize :)
source share