-2

How can I split a string, but when a character repeats, don`t split?

Like:

String a = "aHHHbYY";
String[] b = a.split("");

But I don't want to split every letter just the ones that don`t repeat.

Output would be like:

["a", "HHH", "b", "YY"]
demongolem
  • 9,474
  • 36
  • 90
  • 105
S C
  • 73
  • 7

2 Answers2

0

Your Problem can be solved easily with regular expressions. This could look like this:

String regex = "(?<=(.))(?!\\1)";
String a = "aHHHbYY";
String[] b = a.split(regex);

This gives the exact output you want. If you want a more detailed answer, take a look at this post:

Split regex to extract Strings of contiguous characters

Community
  • 1
  • 1
Pascal Schneider
  • 405
  • 1
  • 5
  • 19
-1

You can use regular expressions as a solution. Here is a example for splitting and separating the chars and removing duplicates.

String input = "aHHHbYY";
String[] result = input.replaceAll("(.)\\1{1,}", "$1").split("");

will get you:

["a", "H", "b", "Y"]
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
GensaGames
  • 5,538
  • 4
  • 24
  • 53
  • 1
    In general, regular expressions aren't that easy to read and understand. But anyway it's always welcome to add some description to your answer. Apart from this, your `result` is `["a", "H", "b", "Y"]`, but the OP wants the array to be `["a", "HHH", "b", "YY"]` – Pascal Schneider Mar 02 '17 at 13:31
  • @PascalSchneider Question was updated, after I answered. Lol. – GensaGames Mar 02 '17 at 17:18
  • If you take a look at the history of the post, my comment still applies. – Pascal Schneider Mar 02 '17 at 18:54