When I split a string in python, adjacent space delimiters are merged:
>>> str = "hi there"
>>> str.split()
['hi', 'there']
In Java, the delimiters are not merged:
$ cat Split.java
class Split {
public static void main(String args[]) {
String str = "hi there";
String result = "";
for (String tok : str.split(" "))
result += tok + ",";
System.out.println(result);
}
}
$ javac Split.java ; java Split
hi,,,,,,,,,,,,,,there,
Is there a straightforward way to get python space split semantics in java?
String.splitaccepts a regular expression, so provide it with one that matches adjacent whitespace:If you want to emulate the exact behaviour of Python’s
str.split(), you’d need to trim as well:Quote from the Python docs on
str.split():So the above is still not an exact equivalent, because it will return
['']for the empty string, but it’s probably okay for your purposes 🙂