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()?
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.
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.
Java split string on empty delimiter returns empty string at the beginning - Intellipaat Community.
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.
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("\\.+");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With