HPSS
HPSS

Reputation: 43

Given a String how to convert it to an Array: Java

so I'm pretty new at Java and StackOverflow (That's what they all say) and I am stuck at the given problem:

My method is given a String e.g.: "[ 25 , 25 , 125 , 125]". Now the method should return an Array of integers representation of the String provided, that is: it should return [25,25,125,125].

Here is a segment of my method. Note: input is the String provided

if(input.charAt(index) == '['){
    index++;
    int start = index;

    while(index <= input.length() && input.charAt(index) != ']'){
        index++;
    }

    String[] arrayStr = input.substring(start, index).split(",");
    int[] arrayInt = new int[4];
    for (int i = 0; i < arrayStr.length; i++){
        arrayInt[i] = Integer.parseInt(arrayStr[i]);
    }
    return arrayInt; 

My code works if input is: "[25,25,125,125]" (If there are no spaces between the numbers). However if there are spaces between the numbers then my code doesn't work and I understand why, but I am struggling to find a way to solve this problem. Any help will be appreciated.

Upvotes: 2

Views: 117

Answers (3)

Pshemo
Pshemo

Reputation: 124215

You can

  1. remove [ and ] and all spaces
  2. split on , to get all tokens
  3. iterate over all tokens

    • parse string number to int
    • add parsed int to result array

So your code can look like

String data = "[ 25 , 25 , 125 , 125]";
String[] tokens = data.replaceAll("\\[|\\]|\\s", "").split(",");
int[] array = new int[tokens.length];
for (int i=0; i<tokens.length; i++){
    array[i]=Integer.parseInt(tokens[i]);
}

Or if you have Java 8 you can use streams like

int[] array = Stream.of(data.replaceAll("\\[|\\]|\\s", "").split(","))
        .mapToInt(number -> Integer.parseInt(number))
        .toArray();

Upvotes: 2

singhakash
singhakash

Reputation: 7919

You can replace the space with empty in the string

input=input.replace(" ","")

Upvotes: 2

giorashc
giorashc

Reputation: 13713

Spaces will fail with Integer.parseInt(arrayStr[i]) (e.g. the string "25 " is not a valid number as it contains a space. (parseInt will throw an exception in such cases.)

However you can solve it quickly by trimming your array elements:

Integer.parseInt(arrayStr[i].trim())

trim() returns a copy of the string without leading/trailing white space

Upvotes: 3

Related Questions