C
C
Chvalov2015-10-27 16:38:42
Java
Chvalov, 2015-10-27 16:38:42

Parse String to int array - Java, how to implement?

There is a text field of type string:

[3389, 3410, 3430, 3450, 3470, 3500, 3520, 3540, 3760, 3780, 3810, 3830, 3850, 3970, 4000, 4140, 4160, 4180, 4210, 4220, 4250, 4300, 4320, 4340, 4360, 4380, 4400, 4420, 4430, 4440]

A string is not an array, but just a string
. How can I parse it and write it to an array of type int ?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
C
Chvalov, 2015-10-27
@Chvalov

Help with this option.

private String b = "[3389, 3410, 3430, 3450, 3470, 3500, 3520, 3540, 3760, 3780, 3810, 3830, 3850, 3970, 4000, 4140, 4160, 4180, 4210, 4220, 4250, 4300, 4320, 4340, 4360, 4380, 4400, 4420, 4430, 4440]";
            String[] items = b.replaceAll("\\[", "").replaceAll("\\]", "").split(",");

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

            for (int i = 0; i < items.length; i++) {
                try {
                    results[i] = Integer.parseInt(items[i].trim());
                } catch (NumberFormatException nfe) {};
            }

Log.d("TEST", Arrays.toString(results));

This is what I get as output: [3389, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

N
nirvimel, 2015-10-27
@nirvimel

First, we split the string .split(",\s");into an array of strings. We create an int array of the same length. Then we loop through the arrays and convert the strings to numbers element by element. numbres[i] = Integer.parseInt(strings[i]);
UPD: This is NOT actually the best solution. I somehow immediately overlooked that this string is a valid object in JSON format, and should be parsed by the appropriate tools. Correct answers given by: EugeneP2 and OnYourLips

O
OnYourLips, 2015-10-27
@OnYourLips

This is json.
www.oracle.com/technetwork/articles/java/json-1973...

P
protven, 2015-10-27
@protven

Well, everyone is so lazy.
stackoverflow.com/questions/7646392/convert-string...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question