Note: My English is some thing poor
How to split String
in java (every 4th and 3rd position).
For example, If i have a String of characters, as:
0110000 1100001 1001100 00110000
(without spaces, spaces are for only representations)
If, I want to split it as:
0110 000 1100 001 1001 100 0011 000
(without spaces)
How to do that in java?
I already have tried it as follows:
jshell> "01100001100001100110000110000".split("(?<=\\G.{4})");
$22 ==> String[8] { "0110", "0001", "1000", "0110", "0110", "0001", "1000", "0" }
As shown it split it into every 4th position
not 4th position && 3rd position
.
Also, Some thing that's
jshell> "01100001100001100110000110000".split("(?<=\\G.{4})|(?<=\\G.{3})");
$24 ==> String[10] { "011", "000", "011", "000", "011", "001", "100", "001", "100", "00" }
Or
jshell> "01100001100001100110000110000".split("(?<=\\G.{4}|\\G.{3})");
$25 ==> String[10] { "011", "000", "011", "000", "011", "001", "100", "001", "100", "00" }
Tried different ways but not not solved my problem. Also on the internet nothing find solution.
My question is that's how to solve this problem. Thanks.
You could first break the string in substrings of length 7 and process each of these substrings by splitting it after the 4th digit:
String string = "01100001100001100110000110000";
String[] array = string.split("(?<=\\G.{7})");
String[] array2= new String[array.length*2];
for(int i = 0; i < array.length; i++) {
String[] temp = array[i].split("(?<=\\G.{4})");
array2[i*2] = temp[0];
if (temp.length > 1) {
array2[i*2+1]= temp[1];
}
}
Of course, you might want to add some additional math to skip the last "null"
array2 ==> String[10] { "0110", "000", "1100", "001", "1001", "100", "0011", "000", "0", null }