cb92 cb92 - 1 year ago 94
Java Question

Identifying set of integers in strings

I'm new to Java, trying to learn more.

How do I identify a contiguous set of integers in a string?

For example, if I have the string "123hh h3ll0 wor1d" the program should output 4 as the answer.

Here's what I've worked on, and as a result, my program outputs 6. I understand why but I don't know how to implement what I want the program to do.

public static void main (String[] args) throws java.lang.Exception
String string = "123hh h3ll0 w0rld";

int count = 0;

if (string.isEmpty())
count = 0;

for (int i = 0; i < string.length(); i++)
char c = string.charAt(i);

if (Character.isDigit(c))



Answer Source

Your program is a good start, but it counts all digits. You need to avoid count++ when you are in a contiguous group of digits. You can do it by adding a boolean flag which you set to true when you see a digit, and then to false when you see a non-digit:

boolean inDigits = false;
for (int i = 0; i < string.length(); i++)
    char c = string.charAt(i);

    if (Character.isDigit(c)) {
        if (!inDigits) count++;
        inDigits = true;
    } else {
        inDigits = false;

Demo 1

A simpler way to find the number of groups is to split on \\d+ (a sequence of one or more digits), count the number of groups you get, and subtract one:


Demo 2

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download