0

I am trying to split a String array and use delimiters to remove any whitespace (including \t) but I am getting an empty element "" for some reason.

My Code:

String temp = "    x = x + 9";
String[] tempArr = temp.split("\\s+");

The result I am getting:

tempArr[0] = ""
tempArr[1] = "x"
tempArr[2] = "="
...

I do not understand why I am getting an empty element in the first index of the array.

4
  • This: "\s+" is a typo, right? It should be: "\\s+". Commented Apr 21, 2019 at 9:17
  • Use .trim() before .split(..) to get rid of leading and trailing white spaces. Commented Apr 21, 2019 at 9:25
  • "I do not understand why I am getting an empty element in the first index of the array." what would you expect to get as result of "AxB".split("x")? And what in case of "xAxB".split("x")? Now simply change x with space. Commented Apr 21, 2019 at 9:38
  • Possible duplicate of How to remove empty results after splitting with regex in Java? Commented Apr 21, 2019 at 12:16

2 Answers 2

2

Change split("\s+") to split("\\s+") and use trim() earlier to get rid of all leading and trailing extra spaces

String[] tempArr = temp.trim().split("\\s+");
Sign up to request clarification or add additional context in comments.

1 Comment

My bad, I only focused on changing \s to \\s (which is unnecessary IMO and can't solve OP real problem because he must be using \\s to get any result, so there is no \s in his code) and missed fact that you also suggested using trim() method which was proper solution here. Sorry for downvote, fixed it.
0

You are using "\\s+" are a delimiter and in your given string " x = x + 9" there are spaces in front of the string, that means the first set of spaces is separating empty word and x.

I will try to give you some example not using spaces:

String temp = ",a,b,c";
String[] tempArr = temp.split(",");

Will result as:

tempArr[0] = ""
tempArr[1] = "a"
tempArr[2] = "b"
tempArr[2] = "c"

Do you see why? Because in front of the first "," there is empty string. It's same with spaces.

If you don't want to have first element empty, use function .trim() as @PRC_noob and @Pshemo already suggested. It will remove spaces from the beginning and the end of your string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.