67

I have one string:

String arr = "[1,2]";

ie "[1,2]" is like a single String.

How do I convert this arr to int array in java?

6
  • 1
    Your example code doesn't compile. Please fix it. That said, have a look at StringTokenizers: download.oracle.com/javase/6/docs/api/java/util/… Oct 4, 2011 at 10:24
  • Are you clear of what you really want to do? Oct 4, 2011 at 10:24
  • Why 8 down votes ...?? Oct 18, 2013 at 17:27
  • 11
    Do not understand why this question is downvoted. It is perfectly clear: convert String which has the following format: [#,#,#,#,...,#] into int[] Jan 23, 2014 at 13:54
  • 1
    Useful, clear question that I'm needing the answer to, so much later. The 50K+ views by now are quite telling of the question quality. +1. Jun 29, 2014 at 2:25

11 Answers 11

105
String arr = "[1,2]";
String[] items = arr.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");

int[] results = new int[items.length];

for (int i = 0; i < items.length; i++) {
    try {
        results[i] = Integer.parseInt(items[i]);
    } catch (NumberFormatException nfe) {
        //NOTE: write something here if you need to recover from formatting errors
    };
}
3
  • 8
    you sir, deserve a medal! thank you so much!! my string looked like this: [["1","2"],["11","5"]...] Aug 12, 2012 at 16:31
  • 2
    this worked well, I just had to add .replaceAll(" ", "") as my string had spaces in between numbers e.g [1313, 1314, 1315] , without replacing spaces I would get my int[] as [1313, 0, 0]
    – Tomas
    Jan 18, 2016 at 14:23
  • String[] items = arr.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(","); could be replaced with String[] items = arr.replaceAll("\\[|\\]|\\s|,", "") Just finished my regex class :)
    – evuazeze
    Apr 20, 2021 at 10:08
60

Using Java 8's stream library, we can make this a one-liner (albeit a long line):

String str = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]";
int[] arr = Arrays.stream(str.substring(1, str.length()-1).split(","))
    .map(String::trim).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));

substring removes the brackets, split separates the array elements, trim removes any whitespace around the number, parseInt parses each number, and we dump the result in an array. I've included trim to make this the inverse of Arrays.toString(int[]), but this will also parse strings without whitespace, as in the question. If you only needed to parse strings from Arrays.toString, you could omit trim and use split(", ") (note the space).

1
  • Thank you for adding this as answer Oct 11, 2015 at 20:15
15
    final String[] strings = {"1", "2"};
    final int[] ints = new int[strings.length];
    for (int i=0; i < strings.length; i++) {
        ints[i] = Integer.parseInt(strings[i]);
    }
1
  • 7
    Nice concise way to implement this. I'm definitely disappointed, though, that Java apparently hasn't thought of a one-liner in one of its libraries for this. Jun 29, 2014 at 2:31
7

It looks like JSON - it might be overkill, depending on the situation, but you could consider using a JSON library (e.g. http://json.org/java/) to parse it:

    String arr = "[1,2]";

    JSONArray jsonArray = (JSONArray) new JSONObject(new JSONTokener("{data:"+arr+"}")).get("data");

    int[] outArr = new int[jsonArray.length()]; 

    for(int i=0; i<jsonArray.length(); i++) {
        outArr[i] = jsonArray.getInt(i);
    }
3

try this one, it might be helpful for you

String arr= "[1,2]";
int[] arr=Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();
4
  • 1
    Hi, welcome to StackOverflow. Given that this is quite an old question, with a lot of popular answers, please edit your question to explain what your answer provides that existing ones don't. Thanks.
    – MandyShaw
    Nov 3, 2018 at 21:08
  • Your answer doesn't work properly with entries like "[123, 456]" Nov 3, 2018 at 21:34
  • please check it now ! Nov 3, 2018 at 21:48
  • I think what @OlivierGrégoire is getting at is that the code only works if each element is a single digit. But it only needs a small tweak: Stream.of(str.replaceAll("[\\[\\]\\ ]", "").split(",")).mapToInt(Integer::parseInt).toArray() Dec 8, 2019 at 12:26
2

Saul's answer can be better implemented splitting the string like this:

string = string.replaceAll("[\\p{Z}\\s]+", "");
String[] array = string.substring(1, string.length() - 1).split(",");
1

You can do it easily by using StringTokenizer class defined in java.util package.

void main()
    {
    int i=0;
    int n[]=new int[2];//for integer array of numbers
    String st="[1,2]";
    StringTokenizer stk=new StringTokenizer(st,"[,]"); //"[,]" is the delimeter
    String s[]=new String[2];//for String array of numbers
     while(stk.hasMoreTokens())
     {
        s[i]=stk.nextToken();
        n[i]=Integer.parseInt(s[i]);//Converting into Integer
       i++;
     }
  for(i=0;i<2;i++)
  System.out.println("number["+i+"]="+n[i]);
}

Output :-number[0]=1 number[1]=2

1
    String str = "1,2,3,4,5,6,7,8,9,0";
    String items[] = str.split(",");
    int ent[] = new int[items.length];
    for(i=0;i<items.length;i++){
        try{
            ent[i] = Integer.parseInt(items[i]);
            System.out.println("#"+i+": "+ent[i]);//Para probar
        }catch(NumberFormatException e){
            //Error
        }
    }
1

If you prefer an Integer[] instead array of an int[] array:

Integer[]

String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(","); 
Integer[] result = Stream.of(parts).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);

int[]

String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(","); 
int[] result = Stream.of(parts).mapToInt(Integer::parseInt).toArray()

This works for Java 8 and higher.

0

In tight loops or on mobile devices it's not a good idea to generate lots of garbage through short-lived String objects, especially when parsing long arrays.

The method in my answer parses data without generating garbage, but it does not deal with invalid data gracefully and cannot parse negative numbers. If your data comes from untrusted source, you should be doing some additional validation or use one of the alternatives provided in other answers.

public static void readToArray(String line, int[] resultArray) {
    int index = 0;
    int number = 0;

    for (int i = 0, n = line.length(); i < n; i++) {
        char c = line.charAt(i);
        if (c == ',') {
            resultArray[index] = number;
            index++;
            number = 0;
        }
        else if (Character.isDigit(c)) {
            int digit = Character.getNumericValue(c);
            number = number * 10 + digit;
        }
    }

    if (index < resultArray.length) {
        resultArray[index] = number;
    }
}

public static int[] toArray(String line) {
    int[] result = new int[countOccurrences(line, ',') + 1];
    readToArray(line, result);
    return result;
}

public static int countOccurrences(String haystack, char needle) {
    int count = 0;
    for (int i=0; i < haystack.length(); i++) {
        if (haystack.charAt(i) == needle) {
            count++;
        }
    }
    return count;
}

countOccurrences implementation was shamelessly stolen from John Skeet

0
String arr= "[1,2]";
List<Integer> arrList= JSON.parseArray(arr,Integer.class).stream().collect(Collectors.toList());
Integer[] intArr = ArrayUtils.toObject(arrList.stream().mapToInt(Integer::intValue).toArray());

Not the answer you're looking for? Browse other questions tagged or ask your own question.