Matoy
Matoy

Reputation: 1818

Count the borders between zeros inside a String in Java

I have a special kind of Strings in Java that has a sequence of zeros and some short sequence of characters between them like those:

"0000000000TT0000TU0000U0"

"0000000000TL"

"0000000000TL0000TM"

I want to count the number of sequences that are different from zeros.

for example:

"0000000000TT0000TU0000U0" will return 3

"0000000000TL" will return 1

"0000000000TL0000TM" will return 2

"000000" will return 0.

Any short and easy way to do it (maybe some Java String build option or regex of some kinde)? Thanks

Upvotes: 1

Views: 47

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174706

Use a negated character class to match any character but not of 0.

Matcher m = Pattern.compile("[^0]+").matcher(s);
int i = 0;
while(m.find()) {
   i = i + 1;
}
System.out.println("Total count " + i);

DEMO

Upvotes: 4

Related Questions