J. Doe J. Doe - 7 months ago 8
Java Question

Splitting a string to a list of integers in java

I want to split a string of form:

" 42 2152 12 3095 2"


into a list of integers, but when I use the
.split(" ")
function I end up with an empty
""
element at the beginning due to the whitespace at the start. Is there a way to split this without the empty element?

Aph Aph
Answer

Use the String.trim() function before you call split on the array. This will remove any white-spaces before and after your original string

For example:

    String original = " 42 2152 12 3095 2"; 
    original = original.trim();
    String[] array = original.split(" ");

To make your code neater, you could also write it as:

    String original = " 42 2152 12 3095 2"; 
    String[] array = original.trim().split(" ");

If we print the array out:

    for (String s : array) {
        System.out.println(s);
     }

The output is:

42
2152
12
3095
2

Hope this helps.