Derrek Whistle
Derrek Whistle

Reputation: 711

Retrieving integers from a string

Say you have a string:

    String numbers = "123 11 4392034 2";

and you want to retrieve each integer in the string (separated by spaces). What is the best way to go about doing this?

Upvotes: 1

Views: 147

Answers (3)

Susanta
Susanta

Reputation: 319

String[] tokens = "123 234".split("\\s")

for(String token : tokens){
  println Integer.parseInt(token)
}

Links:

  1. Run the groovy script: http://groovyconsole.appspot.com/script/1031001
  2. Java Pattern class at http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
  3. Java regular expression tutorial at http://docs.oracle.com/javase/tutorial/essential/regex

Notes

  1. \s denotes white space character class, [ \t\n\x0B\f\r]. Extra '\' to escape the first one as '\' is itself an escape character. See http://docs.oracle.com/javase/tutorial/java/data/characters.html.

Upvotes: 0

Azad
Azad

Reputation: 5055

String numbers = "123 11 4392034 2";
String [] num = numbers.split(" ");

Then use this method to retrive the array of integers:

public int[] getIntegerArray(String[] numbers) throws NumberFormatException {
    if (numbers!= null) {
        int intarray[] = new int[numbers.length];
        for (int i = 0; i < numbers.length; i++) {
            intarray[i] = Integer.parseInt(numbers[i]);
        }
        return intarray;
    }
    return null;
}

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240870

split() by space and Integer.parseInt() on each array element

Upvotes: 6

Related Questions