There is no obvious regex pattern to do this. Perhaps this can be done using String.split , but I would just use substring as follows:
String s = "12345678abcdefgh"; final int mid = s.length() / 2; String[] parts = { s.substring(0, mid), s.substring(mid), }; System.out.println(Arrays.toString(parts));
The above would split the odd length of String by part[1] one character longer than part[0] . If you need it the other way around, just define mid = (s.length() + 1) / 2;
split n-piece
You can also do something similar to split the string into N-parts:
static String[] splitN(String s, final int N) { final int base = s.length() / N; final int remainder = s.length() % N; String[] parts = new String[N]; for (int i = 0; i < N; i++) { int length = base + (i < remainder ? 1 : 0); parts[i] = s.substring(0, length); s = s.substring(length); } return parts; }
Then you can do:
String s = "123456789"; System.out.println(Arrays.toString(splitN(s, 2))); // "[12345, 6789]" System.out.println(Arrays.toString(splitN(s, 3))); // "[123, 456, 789]" System.out.println(Arrays.toString(splitN(s, 5))); // "[12, 34, 56, 78, 9]" System.out.println(Arrays.toString(splitN(s, 10))); // "[1, 2, 3, 4, 5, 6, 7, 8, 9, ]"
Note that this allows earlier parts to hold extra characters, and also works when the number of parts is greater than the number of characters.
application
In the above code:
?: is a conditional statement called a ternary operator./ performs integer division. 1 / 2 == 0 .% performs an integer remainder operation. 3 % 2 == 1 . In addition, -1 % 2 == -1 .
References
Related Questions