Convert String to int array in java

I have one line

String arr= "[1,2]"; 

ie "[1,2]" as one line

How to convert this arr to int array in java

+42
java
04 Oct '11 at 10:20
source share
7 answers
 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 }; } 
+75
04 Oct '11 at 10:23
source share

Using the Java 8 thread library, we can make this one-line (albeit long):

 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 elements of the array, trim removes any spaces around the number, parseInt parses each number, and we unload the result into an array. I have included trim to make it inverse to Arrays.toString(int[]) , but it will also parse strings without spaces, as in the question. If you only need to parse the strings from Arrays.toString , you can omit trim and use split(", ") (note the space).

+38
Sep 15 '14 at 0:43
source share
  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]); } 
+15
04 Oct 2018-11-11T00:
source share

It looks like JSON - this may be excessive, depending on the situation, but you might 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); } 
+5
04 Oct 2018-11-11T00:
source share

Saul's answer could be better implemented by dividing the line as follows:

 string = string.replaceAll("[\\p{Z}\\s]+", ""); String[] array = string.substring(1, string.length() - 1).split(","); 
+1
07 Oct '15 at 9:40
source share

In hard loops or on mobile devices, it is not recommended to create a lot of garbage through short-lived String objects, especially when analyzing long arrays.

The method in my answer parses data without generating garbage, but it doesn’t process invalid data gracefully and cannot parse negative numbers. If your data comes from an unreliable source, you should perform additional verification or use one of the alternatives provided in the 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; } 

The execution of countOccurrences was shamelessly stolen from John Skeet

0
Dec 12 '14 at 14:23
source share

You can do this easily using the StringTokenizer class defined in the 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

0
Feb 08 '15 at 18:47
source share



All Articles