简体   繁体   中英

What is the best way to split String in java, after every 4th an 3rd position?

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 }

try this :

String a ="01100001100001100110000110000";
    List<String> stringList = new ArrayList();
    while (a.length()>=3)
    {
        if(a.length()>=4)
        {
            stringList.add(a.substring(0,4));
            a=a.substring(4,a.length());
            if(a.length()>=3)
            {
                stringList.add(a.substring(0,3));
                a=a.substring(3,a.length());
            }
        }
    }
    stringList.forEach(s-> System.out.println(s));

In latest Java version (eg java 11), You can write short method as follows:

void btnEncryptOnAction(ActionEvent event) {
var input = "01100001100001100110000110000";
String[] parts = input.split("(?<=\\G.{7})");
for (var p : parts) {
    String[] p2 = p.split("(?<=\\G.{4})");
    System.out.print(Arrays.asList(p2)); // to print as array list
}

The output is:

[0110, 000][1100, 001][1001, 100][0011, 000][0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM