[java] Convert String to int array in java

I have one string

String arr= "[1,2]";

ie "[1,2]" is like a single string

How do convert this arr to int array in java

This question is related to java arrays string

The answer is


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


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


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);
    }

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).


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.


    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
        }
    }

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
    };
}

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(",");

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());

try this one, it might be helpful for you

String arr= "[1,2]";
int[] arr=Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();

    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]);
    }

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript