views:

138

answers:

3

Users may want to delimit numbers as they want.

What is the most efficient (or a simple standard function) to extract all the (natural) numbers from a string?

A: 

If you know the delimiter, then:

String X = "12,34,56";
String[] y = X.split(","); // d=delimiter
int[] z = new int[y.length];
for (int i = 0; i < y.length; i++ )
{
    z[i] = java.lang.Integer.valueOf(y[i]).intValue();
}

If you don't, you probably need to pre-process - you could do x.replace("[A-Za-z]", " "); and replace all characters with spaces and use space as the delimiter.

Hope that helps - I don't think there is a built-in function.

Ninefingers
+5  A: 

You could use a regular expression. I modified this example from Sun's regex matcher tutorial:

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Test {

    private static final String REGEX = "\\d+";
    private static final String INPUT = "dog dog 1342 dog doggie 2321 dogg";

    public static void main(String[] args) {
       Pattern p = Pattern.compile(REGEX);
       Matcher m = p.matcher(INPUT); // get a matcher object
       while(m.find()) {
           System.out.println("start(): "+m.start());
           System.out.println("end(): "+m.end());
       }
    }
}

It finds the start and end indexes of each number. Numbers starting with 0 are allowed with the regular expression \d+, but you could easily change that if you want to.

Mark Byers
+1  A: 

I'm not sure I understand your question exactly. But if all you want is to pull out all non-negative integers then this should work pretty nicely:

String foo = "12,34,56.0567 junk 6745 some - stuff tab tab 789";
String[] nums = foo.split("\\D+");

// nums = ["12", "34", "56", "0567", "6745", "789"]

and then parse out the strings as ints (if needed).

Rob Van Dam