-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?

2
  • Trim the string first. Commented Sep 28, 2018 at 19:50
  • .trim() would work ? Commented Sep 28, 2018 at 19:51

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.