Bohemian
Bohemian

Reputation: 425083

Split a string between repeating characters

I want to take any given string and split it based on repeating characters.

As an example, if I were to input the string abcaaabbc, I would want to output an array of strings equal to: [abca, a, ab, bc]. Each time a character repeats, I want to start a new string.

Doing this with a loop is possible, of course, but I am wondering if I can achieve it using the String.split() method. If so - what would the RegEx be?

Upvotes: 8

Views: 1995

Answers (2)

Dan
Dan

Reputation: 1033

From a performance perspective, I would stick with a loop. It runs in O(n) time. The string.split(regex) has been known to be slow. I recently used it in place of a loop and found that it was O(n^2) compared to the O(n) loop.

K.I.S.S principal works here

Upvotes: 0

Prince John Wesley
Prince John Wesley

Reputation: 63698

Tokenize the input string where previous character(look-behind (?<=(.))) is same as next character(look-ahead (?=\\1)) and \1 captures (.).

    String str = "abcbabaaabbc";
    String regex = "(?<=(.))(?=\\1)";        
    System.out.println(Arrays.toString(str.split(regex)));

Upvotes: 13

Related Questions