-4

I need to put all numeric values stored in a String into an array:

String str = "12,1,222,55";

If I do this, then it will merge all numbers:

str = str.replaceAll("\\D+","");

How to get something like this?:

int[] result = new int[]{12,1,122,55};
2
  • 5
    look up string.split and Integer.parseInt in the java docs Commented Mar 2, 2015 at 16:30
  • 1
    Simply don't merge. Just split by , and covert element to int and store an array. Commented Mar 2, 2015 at 16:31

4 Answers 4

3

First split the string. Then parse each element in String array to new array

String[] s=str.split("\\D+");
int[] intarray=new int[s.length];
for(int i=0;i<s.length;i++){
   intarray[i]=Integer.parseInt(s[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

2

Just split your input according to one or more non-digit characters and then convert the datatype of each element to integer.

String[] parts = str.split("\\D+");

Comments

1
String[] numbers = str.split(",");

And add number one by one to int[] with Integer.parseInt(numbers[i]);

If you don't know the exact size of the input string, I recommend using ArrayList for this purpose. If you know there will be 4 values then go with an array.

Comments

1

Split str on , and map the elements into integers using Integer#parseInt.

Demo:

import java.util.Arrays;

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

        String str = "12,1,222,55";

        int[] array = Arrays.stream(str.split(","))
                            .mapToInt(Integer::parseInt)
                            .toArray();

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

    }
}

Output:

[12, 1, 222, 55]

Alternatively,

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 str = "12,1,222,55";
        
        int[] array = Pattern.compile("\\d+")
                        .matcher(str)
                        .results()
                        .map(MatchResult::group)
                        .mapToInt(Integer::parseInt)
                        .toArray();

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

    }
}

Output:

[12, 1, 222, 55]

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.