we need help how to write the regex for string.split so we can split a string in half.
thanks.
There's no obvious regex pattern that would do this. It may be possible to do this with String.split
, but I'd just use substring
like this:
String s = "12345678abcdefgh";
final int mid = s.length() / 2;
String[] parts = {
s.substring(0, mid),
s.substring(mid),
};
System.out.println(Arrays.toString(parts));
// "[12345678, abcdefgh]"
The above would split an odd-length String
with part[1]
one character longer than part[0]
. If you need it the other way around, then simply define mid = (s.length() + 1) / 2;
split
You can also do something like this to split a 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 favors the earlier parts to hold the extra characters, and it also works when the number of parts is more than the number of characters.
In the above code:
?:
is the conditional operator, aka the ternary operator./
performs integer division. 1 / 2 == 0
.%
performs integer remainder operation. 3 % 2 == 1
. Also, -1 % 2 == -1
.You really don't need a regex for this. Just use substring()
.
int midpoint = str.length() / 2;
String firstHalf = str.substring(0, midpoint);
String secondHalf = str.substring(midpoint);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With