-1

I know how to split a string by space as the following:

String[] array = string.split(" ");

This works great until I try to split string that starts with a space like

" I like apple"

The result looks something like this:

{"", "I", "like", "apple"}

How can I split the string so it only keeps strings that is not empty?

Terence Lyu
  • 319
  • 1
  • 3
  • 13

2 Answers2

2

You can call string.trim()and then string.split(" "). The trim() method removes spaces before the first non-space-character and after the last non-space-character.

Pablo Hildo
  • 143
  • 6
1

To remove leading and trailing spaces, you can use .trim().

String[] array = string.trim().split(" ");
benjamin c
  • 2,278
  • 15
  • 25