I have some String
s consisting of only digits, and I want to split it whenever the character changes.
For example:
"11101100112021120"
goes to: {"111", "11", "11", "2", "2", "11", "2"}
"222222222"
goes to {"222222222"}
"222222122"
goes to {"222222", "1", "22"}
"000000000"
goes to {}
"0000100000"
goes to {"1"}
"11121222212112133321"
goes to {"111", "2", "1", "2222", "1", "2", "11", "2", "1", "333", "2", "1"}
I want a nice way to do this.
I know two ways to go about this: just brute forcing, or adding section by section. Or, I could go through and remove all 0's and replace with a 0, then add 0's when characters change, and then just do a split on 0's, but both of those ways just look dumb. If anyone has any idea on a better/prettier way to do this, regex or logic, it'd be nice.
This seems to work like you expect
data.split("0+|(?<=([1-9]))(?=[1-9])(?!\\1)");
Test:
String[] tests = { "11101100112021120", "222222222", "222222122",
"000000000", "0000100000", "11121222212112133321" };
for (String data : tests) {
System.out.println(data + " ->" + Arrays.toString(data.split("0+|(?<=([1-9]))(?=[1-9])(?!\\1)")));
System.out.println("-----------------------");
}
output:
11101100112021120 ->[111, 11, 11, 2, 2, 11, 2]
-----------------------
222222222 ->[222222222]
-----------------------
222222122 ->[222222, 1, 22]
-----------------------
000000000 ->[]
-----------------------
0000100000 ->[, 1] // <-- only problem - empty first element
-----------------------
11121222212112133321 ->[111, 2, 1, 2222, 1, 2, 11, 2, 1, 333, 2, 1]
-----------------------
Unfortunately leading zeros will let array to contain additional empty String. To get rid of it you can earlier remove these zeros with data.replaceFirst("^0+(?=[^0])", "")
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