Java String.split () how to prevent an empty element in a new array

I have a String like

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

The test [] includes 4 elements:

 hello are you 

How to simply create three non-empty elements using split ()?

+6
source share
1 answer

You can use a quantifier

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

To handle the leading character . which you could do:

 String[] array = ".hello.are..you".replaceAll("^\\.", "").split("\\.+"); 
+9
source

All Articles