Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String.split(), how to prevent empty element in the new array

Tags:

java

string

split

I have a String like

String s="hello.are..you";
String test[]=s.split("\\.");

The test[] includes 4 elements:

hello
are

you

How to just generate three not empty elements using split()?

like image 519
Jason Z Avatar asked Aug 12 '15 23:08

Jason Z


People also ask

Can string split return empty array?

Using split()When the string is empty and no separator is specified, split() returns an array containing one empty string, rather than an empty array. If the string and separator are both empty strings, an empty array is returned.

What happens if you split an empty string?

If the delimiter is an empty string, the split() method will return an array of elements, one element for each character of string. If you specify an empty string for string, the split() method will return an empty string and not an array of strings.

What happens when you split an empty string in Java?

Java split string on empty delimiter returns empty string at the beginning - Intellipaat Community.

Does string split preserve order?

Yes, . split() always preserves the order of the characters in the string. Think of it this way. Your string is like a rectangular slice of pizza with stripes on it.


1 Answers

You could use a quantifier

String[] array = "hello.are..you".split("\\.+");

To handle a leading . character you could do:

String[] array = ".hello.are..you".replaceAll("^\\.",  "").split("\\.+");
like image 101
Reimeus Avatar answered Oct 08 '22 06:10

Reimeus