Convert String to int array in java

匿名 (未验证) 提交于 2019-12-03 02:08:02

问题:

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

回答1:

String arr = "[1,2]"; String[] items = arr.replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("\\s", "").split(",");  int[] results = new int[items.length];  for (int i = 0; i 


回答2:

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



回答3:

    final String[] strings = {"1", "2"};     final int[] ints = new int[strings.length];     for (int i=0; i 


回答4:

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


回答5:

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


回答6:

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 

countOccurrences implementation was shamelessly stolen from John Skeet



回答7:

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

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!