Jennifer
Jennifer

Reputation: 351

How to split string if different character occur?

I have a string like below:

String str = "77755529";

I want to split this string if different number occur i.e result should be like below after splitting :

str1 = "777";
str2 = "555";
str3 = "2";
str4 = "9";

I tried it with split but could not make it.

Upvotes: 4

Views: 144

Answers (2)

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

Try this:

String   str = "77755529";
String[] res = str.split("(?<=(.))(?!\\1)");

IDEONE SAMPLE

Upvotes: 8

Avinash Raj
Avinash Raj

Reputation: 174696

You may do matching.

List<String> lst = new ArrayList<String>();
Matcher m = Pattern.compile("(\\d)\\1+|\\d+").matcher(s);
while(m.find()) {
   lst.add(m.group());
}
System.out.println(lst);

Upvotes: 2

Related Questions