1

I need to extract integers from a String into an array.

I've already got the integers, but I wasn't able to place them into an array.

public static void main(String[] args) {
    String line = "First number 10, Second number 25, Third number 123";
    String numbersLine = line.replaceAll("[^0-9]+", "");
    int result = Integer.parseInt(numbersLine);

    // What I want to get:
    // array[0] = 10;
    // array[1] = 25;
    // array[2] = 123;
}
2
  • Are u sure you will be getting comma separated string? If yes then the first substring with a comma and then perform the same operation. Commented Oct 4, 2018 at 11:31
  • Possible duplicate of How to extract numbers from a String into an array Commented Oct 4, 2018 at 11:32

8 Answers 8

4

You can use a regular expression to extract numbers:

String s = "First number 10, Second number 25, Third number 123 ";
Matcher matcher = Pattern.compile("\\d+").matcher(s);

List<Integer> numbers = new ArrayList<>();
while (matcher.find()) {
    numbers.add(Integer.valueOf(matcher.group()));
}

\d+ stands for any digit repeated one or more times.

If you loop over the output, you will get:

numbers.forEach(System.out::println);

// 10
// 25
// 123

Note: This solution does only work for Integer, but that is also your requirement.

Sign up to request clarification or add additional context in comments.

Comments

1

Instead of replacing characters with empty string, replace with a space. And then split over it.

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        String line = "First number 10, Second number 25, Third number 123 ";
        String numbersLine = line.replaceAll("[^0-9]+", " ");

        String[] strArray = numbersLine.split(" ");

        List<Integer> intArrayList = new ArrayList<>();

        for (String string : strArray) {
            if (!string.equals("")) {
                System.out.println(string);
                intArrayList.add(Integer.parseInt(string));
            }
        }

        // what I want to get:
        // int[0] array = 10;
        // int[1] array = 25;
        // int[2] array = 123;
    }
}

Comments

1

Given you have the numbers a string like "10, 20, 30", you can use the following:

String numbers = "10, 20, 30";

String[] numArray = nums.split(", ");

ArrayList<Integer> integerList = new ArrayList<>();

for (int i = 0; i < x.length; i++) {
    integerList.add(Integer.parseInt(numArray[i]));
}

Comments

1

You could try using the stream api:

String input = "First number 10, Second number 25, Third number 123";

int[] anArray = Arrays.stream(input.split(",? "))
    .map(s -> {
        try {
            return Integer.valueOf(s);
        } catch (NumberFormatException ignored) {
            return null;
        }
    })
    .filter(Objects::nonNull)
    .mapToInt(x -> x)
    .toArray();


System.out.println(Arrays.toString(anArray));

and the output is :

[10, 25, 123]

And the regex.replaceAll version will be:

int[] a = Arrays.stream(input.replaceAll("[^0-9]+", " ").split(" "))
    .filter(x -> !x.equals(""))
    .map(Integer::valueOf)
    .mapToInt(x -> x)
    .toArray();

where output is the same.

Comments

1

Split with non-digits, then parse the result:

List<Integer> response = Arrays.stream(line.split("\\D+"))
        .filter(s -> !s.isBlank())
        .map(Integer::parseInt)
        .toList();

Comments

1

Extract the integer strings using the pattern, \d+ (i.e. one or more digits) and map them into integers using Integer#parseInt.

int[] array = Pattern.compile("\\d+")
                     .matcher(line)
                     .results()
                     .map(MatchResult::group)
                     .mapToInt(Integer::parseInt)
                     .toArray();

Demo:

import java.util.Arrays;
import java.util.List;
import java.util.regex.MatchResult;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {

        String line = "First number 10, Second number 25, Third number 123";
        
        int[] array = Pattern.compile("\\d+")
                        .matcher(line)
                        .results()
                        .map(MatchResult::group)
                        .mapToInt(Integer::parseInt)
                        .toArray();

        System.out.println(Arrays.toString(array));

    }
}

Output:

[10, 25, 123]

Comments

0
public static void main(String args[]) {

        String line = "First number 10, Second number 25, Third number 123 ";

        String[] aa=line.split(",");
        for(String a:aa)
        {
            String numbersLine = a.replaceAll("[^0-9]+", "");
            int result = Integer.parseInt(numbersLine);
            System.out.println(result);

        }

}

Comments

0

Working code:

public static void main(String[] args) 
{
    String line = "First number 10, Second number 25, Third number 123 ";
    String[] strArray= line.split(",");
    int[] integerArray =new int[strArray.length];

    for(int i=0;i<strArray.length;i++)
        integerArray[i]=Integer.parseInt(strArray[i].replaceAll("[^0-9]", ""));
    for(int i=0;i<integerArray.length;i++)
        System.out.println(integerArray[i]);
        //10
        //15 
        //123
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.