简体   繁体   中英

Splitting a string around sequences of char in Java

How can I split a string in Java around sequences of a character which are multiple of a particular number? Example: I have a binary string

101010100010000001110101110111

and I want to split it around sequences of zero which are multiple of 3, ie it should return

[1010101, 1, 1110101110111]

(it should take into regex sequences of zero which are divisible by 3, in this case 000 and 000000)

I tried with split("[0{3}]+") but it doesn't work.

I think split("(0{3})+") should solve it. Putting something between [] means that you are trying to look for certain characters that is in that block.

UPDATE

If we want what is desired in the comments it should be like this: split("(?<!0)(0{3})+(?!(0{1,2}))") . It is a bit more complex, but it should give the desired output.

So lets say we have 100001 as input. The part (?<!0) will make sure there is never a 0 at the beginning, otherwise results may look like [10, 1] . And (?!(0{1,2})) checks if there are 1 or 2 remaining 0 .

This will give [100001] with the given input. With input 1000100001 it will result in [1, 100001]

Try

String str = "101010100010000001110101110111";
String[] strArray = str.split("(0{3})+");
System.out.println(Arrays.toString(strArray));

Try

class Scratch {
    public static void main(String[] args) {
        String s = "101010100010000001110101110111";

        for (String el : s.split("(0{3})+")) {
            System.out.println(el);
        }

    }
}

Use regular expressions for splitting Strings.

It is a very powerful tool. Almost a language itself.

In your case :

s.split("0{3,}")

See you.

David.

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