If I had the following
str1 = " Just a test "
str2 = " "
l1 = str1.strip().split()
l2 = str2.strip().split()
I'd get
l1 = ["Just", "a", "test"]
l2 = []
How would I accomplish this in Java?
Split() String method in Java with examples. The string split() method breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.
Definition and Usage. The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
There's no difference. split() ignores whitespace on the ends of the input by default. People call strip() first either because they think it's clearer or because they don't know this behavior of split() .
You could use String.trim()
and String.split(String)
(which takes a regular expression). Something like,
String str1 = " Just a test ";
String str2 = " ";
String[] l1 = str1.trim().split("\\s+");
String[] l2 = str2.trim().split("\\s+");
System.out.println(Arrays.toString(l1));
System.out.println(Arrays.toString(l2));
Outputs (the requested)
[Just, a, test]
[]
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