简体   繁体   English

在重复字符之间拆分字符串

[英]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] . 举个例子,如果我输入字符串abcaaabbc ,我想输出一个等于的字符串数组: [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. 当然,可以使用循环执行此操作,但我想知道是否可以使用String.split()方法实现它。 If so - what would the RegEx be? 如果是这样 - RegEx会是什么?

Tokenize the input string where previous character(look-behind (?<=(.)) ) is same as next character(look-ahead (?=\\\\1) ) and \\1 captures (.) . 对前一个字符(后视(?<=(.)) )与下一个字符(前瞻(?=\\\\1) )相同并且\\1捕获(.)的输入字符串进行标记。

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

From a performance perspective, I would stick with a loop. 从性能的角度来看,我会坚持循环。 It runs in O(n) time. 它在O(n)时间内运行。 The string.split(regex) has been known to be slow. 已知string.split(正则表达式)很慢。 I recently used it in place of a loop and found that it was O(n^2) compared to the O(n) loop. 我最近使用它代替循环,发现与O(n)循环相比它是O(n ^ 2)。

KISS principal works here KISS校长在这里工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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